部分隐藏电子邮件地址 - JavaScript

3

如何使用Javascript部分隐藏电子邮件地址?

examplemail@domain.com => ex**pl**ai*@domain.com

我修改了下面的代码,但没有得到需要的结果,它只返回了这个结果:

exam*******@domain.com

email.replace(/(.{4})(.*)(?=@)/, function (gp1, gp2, gp3) {
for (let i = 0; i < gp3.length; i++) {
  gp2 += "*";
}
return gp2;

});


我也会隐藏域名。 - Melchia
这是只针对一个电子邮件地址吗?还是可以是包含多个电子邮件地址的字符串? - The fourth bird
5个回答

5
你可以搜索四个字符组并将两个字符组替换为一个,直到找到@符号。

const
    mask = string => string.replace(
        /(..)(.{1,2})(?=.*@)/g,
        (_, a, b) => a + '*'.repeat(b.length)
    );

console.log(mask('examplemail@domain.com'));


1
@Thefourthbird,需要一个获取长度的函数。请查看编辑内容。 - Nina Scholz

0
如果你只想替换靠近 @ 符号的数字,并根据长度添加 *,可以这样做。
 const separatorIndex = email.indexOf('@');
    if (separatorIndex < 3)
        return email.slice(0, separatorIndex).replace(/./g, '*')
            + email.slice(separatorIndex);

    const start = separatorIndex - Math.round(Math.sqrt(separatorIndex)) - 1;

    const masked = email.slice(start, separatorIndex).replace(/./g, '*');
    return email.slice(0, start) + masked + email.slice(separatorIndex);

0

只需这样做

function maskFunc(x) {
    var res = x.replace(/(..)(.{1,2})(?=.*@)/g,
     (beforeAt, part1, part2) => part1 + '*'.repeat(part2.length)
    );  
    
    return res
}

console.log(maskFunc('emailid@domain.com'));


0
作为接受答案的正则表达式,我建议确保只匹配单个@符号,通过使用否定字符类[^\s@]来匹配除空格字符或@本身之外的任何字符。
这样,您也可以将其用于多个电子邮件地址,因为使用多个@符号的(?=.*@)可能会产生意外结果。
([^\s@]{2})([^\s@]{1,2})(?=[^\s@]*@)

正则表达式演示


在你尝试的模式中,你使用了(.{4})来匹配任意字符4次。可以使用正向后瞻来重复4个字符。然后你就可以只获取匹配项而不需要分组。
首先在左侧断言一个空格边界。然后从2个字符的偏移量开始,可选地重复4个字符。
然后匹配1或2个字符,并在右侧断言@。

const partialMask = s => s.replace(
  /(?<=(?<!\S)[^\s@]{2}(?:[^\s@]{4})*)[^\s@]{1,2}(?=[^\s@]*@)/g,
  m => '*'.repeat(m.length)
);
console.log(partialMask("examplemail@domain.com"));


0
这将是解决您问题的一个方法:
function f(mail) {
  let parts = mail.split("@");
  let firstPart = parts[0];
  let encrypt = firstPart.split("");
  let skip = 2;
  for (let i = 0; i < encrypt.length; i += 1) {
    if (skip > 0) {
      skip--;
      continue;
    }
    if (skip === 0) {
      encrypt[i] = "*";
      encrypt[i + 1] = "*";
      skip = 2;
      i++;
    }
  }
  let encryptedMail = `${encrypt.join("")}@${parts.slice(1)}`;
  return encryptedMail;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接