最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Masking phone number with regex in javascript - Stack Overflow

programmeradmin5浏览0评论

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:

/[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. 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

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:

/[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. 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
Share Improve this question edited Aug 8, 2019 at 5:35 Jitender asked Aug 7, 2019 at 12:54 JitenderJitender 7,96932 gold badges116 silver badges218 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

Replace {3} with {2,3} to match two or three digits.

/[0-9]{3}\.[0-9]{2,3}\.([0-9]{3})/

For reference see e.g. MDN

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.

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. Then, in replace cb function, you can use length to know if you must put a new x.

发布评论

评论列表(0)

  1. 暂无评论