3

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
0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

That will not help OP, since the second part (between dots) needs to be masked with x.
2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.