Jitender
Jitender

Reputation: 7969

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

Upvotes: 3

Views: 7309

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

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.

Upvotes: 2

guijob
guijob

Reputation: 4488

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.

Upvotes: 1

Aedvald Tseh
Aedvald Tseh

Reputation: 1917

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

Upvotes: 5

Related Questions