使用js regex隐藏除最后4之外的所有'数字'



我正在努力寻找合适的正则表达式来替换我的电话号码字符串。目标是屏蔽除最后4个之外的所有numbers

我有/d(?=d{4})/g, "*",但它不会与其他符号,如(-工作

例如

'1234567890'.replace(/d(?=d{4})/g, "*");->******7890(作品)

'(123)456-7890'.replace(/d(?=d{4})/g, "*");->(123)456-7890(不工作,我想在这里(***)***-7890)

所以我希望能够忽略除数字以外的所有符号

使用

/d(?=(?:D*d){4})/g

看到证据。

--------------------------------------------------------------------------------
d                       digits (0-9)
--------------------------------------------------------------------------------
(?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
(?:                      group, but do not capture (4 times):
--------------------------------------------------------------------------------
D*                      non-digits (all but 0-9) (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
d                       digits (0-9)
--------------------------------------------------------------------------------
){4}                     end of grouping
--------------------------------------------------------------------------------
)                        end of look-ahead

参见代码示例:

const strings = ["(123)456-7890", "1234567890"]
strings.forEach( phone_number =>
console.log(phone_number.replace(/d(?=(?:D*d){4})/g, "*"))
)

您的regexp只匹配紧跟其后的4个数字。但是在第二个例子中,在数字和最后4位数字之间有标点符号需要替换。你需要考虑到这一点,通过将.*放在开头来匹配两者之间的任何内容。

result = '1234567890'.replace(/d(?=.*d{4})/g, "*");
console.log(result);
result = '(123)456-7890'.replace(/d(?=.*d{4})/g, "*");
console.log(result);

最新更新