[英]Masking phone number with regex in javascript
My application has a specific phone number format which looks like 999.111.222
, which I have a regex pattern to mask it on front-end: 我的应用程序有一个特定的电话号码格式,看起来像
999.111.222
,我有一个正则表达式模式,以掩盖它在前端:
/[0-9]{3}\.[0-9]{3}\.([0-9]{3})/
But recently, the format was changed to allow the middle three digits to have one less digit, so now both 999.11.222
and 999.111.222
match. 但最近,格式被更改为允许中间三位数字少一个数字,所以现在
999.11.222
和999.111.222
匹配。 How can I change my regex accordingly? 如何相应地更改我的正则表达式?
"999.111.222".replace(/[0-9]{3}\.[0-9]{3}\.([0-9]{3})/, '<div>xxx.xxx.$1</div>')
expected output: 预期产量:
"999.111.222" // xxx.xxx.222
"999.11.222" // xxx.xx.222
Use 采用
console.log( "999.11.222".replace(/[0-9]{3}\\.([0-9]{2,3})\\.([0-9]{3})/, function ($0, $1, $2) { return '<div>xxx.' + $1.replace(/\\d/g, 'x') + '.' + $2 + '</div>'; }) )
The ([0-9]{2,3})
first capturing group will match 2 or 3 digits, and in the callback method used as the replacement argument, all the digits from th first group are replaced with x
. ([0-9]{2,3})
第一个捕获组将匹配2或3个数字,并且在用作替换参数的回调方法中,来自第一个组的所有数字都被替换为x
。
You may further customize the pattern for the first set of digits, too. 您也可以进一步自定义第一组数字的模式。
In fact, you should change not only your regex but also your callback replace function: 实际上,您不仅应该更改正则表达式,还应该更改回调替换功能:
const regex = /[0-9]{3}\\.([0-9]{2,3})\\.([0-9]{3})/; const cbFn = (all, g1, g2) =>`<div>xxx.xx${(g1.length === 3 ? 'x' : '')}.${g2}</div>`; const a = "999.11.222".replace(regex, cbFn); const b = "999.111.222".replace(regex, cbFn); console.log(a, b);
To change regex you could add a term with {2,3}
quantifier, as already suggested, and create a new group. 要更改正则表达式,您可以添加带有
{2,3}
量词的术语,如已建议的那样,并创建一个新组。 Then, in replace cb function, you can use length to know if you must put a new x
. 然后,在替换cb函数中,您可以使用length来知道是否必须放置一个新的
x
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.