我想用星号 (*) 屏蔽从 API 返回的数据。例如,如果要从 API 返回一个地址,我只希望前 2 个字母可见。
示例:Lorem Ipsum 只是印刷和排版行业的虚拟文本。
我想要的:Lo*** Ip*** is si**** du*** .....
我创建了一个示例 API,但我不知道如何找到解决方案。我以为我可以通过替换将文本转换为星号,但我不知道如何显示前两个字母。
演示:Here
如果您对我应该做什么有任何想法并分享,我将不胜感激。
答案 0 :(得分:2)
你可以这样做
const s = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
function hideWord(w) {
if (w.length < 3) return w;
return w.substring(0, 2) + '*'.repeat(w.length-2);
}
console.log(s.split(" ").map(hideWord).join(" "));
输出是
Lo*** Ip*** is si**** du*** te** of th* pr****** an* ty********* in*******
将字符串拆分为单词,然后将每个单词映射到其隐藏版本的顶部并重新加入。要映射它,只需按原样返回任何 1 或 2 个字母长度的单词,而对于其他单词,则取前两个字符的子字符串并用星号填充其余字符。
如果您希望能够从多个地方调用它并避免重新定义它,您也可以将整个批次包装在一个函数中。
function hideWords(s) {
return s.split(" ").map(hideWord).join(" ");
}
console.log(hideWords(s));
答案 1 :(得分:2)
我会将 regex 与 lookbehind assertion 一起使用
const text = 'Lorem Ipsum is simply dummy text of the printing & typesetting industry';
const result = text.replaceAll(/(?<=\w{2,})\w/g, '*');