Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

/[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
like image 283
Jitender Avatar asked Jan 22 '26 10:01

Jitender


1 Answers

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

like image 167
Aedvald Tseh Avatar answered Jan 24 '26 00:01

Aedvald Tseh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!