Mask and insert hyphen after every 3 digits

108 Views Asked by At

I am trying to replace the below string like below:

var phone = "9871234567"
result = xxx-xxx-4567

Below is the js code I have worked upon, but this is not giving me the correct result.

var lastphdigit = phone.replace(/\d(?=(?:\D*\d){4})/g, "x");
var lastphdighyp = lastphdigit.replace(/.{3}(?!$)/g, '$&-'); //xxx-xxx-456-7
3

There are 3 best solutions below

2
depperm On

Regex is not necessary for this problem. Using slice would be much simpler, just get the last 4 digits

var phone = "9871234567"
console.log(`xxx-xxx-${phone.slice(6)}`)

0
Wilco On

Inspired by the comment @depperm gave, why not try this? We slice off 4 digits from the phone number, starting at the end, and then append it to a static string.

var phone = "9871234567";
var maskedPhone = "xxx-xxx-" + phone.slice(-4);
console.log(maskedPhone)

This way, if the amount of digits in the phone number is variable, you will still always get the last 4 digits unmasked. IF this is a consideration, you should also count the amount of digits in the original phone number, and add x's accordingly.

0
The fourth bird On

If there should be only digits in the string and your JavaScript environment accepts a lookbehind assertion, you can assert optional digits to the left, match 3 digits while asserting 2 or more digits to the right:

(?<=^\d*)\d{3}(?=\d{2,}$)

Regex demo

const phone = "9871234567"
const result = phone.replace(/(?<=^\d*)\d{3}(?=\d{2,}$)/g, "xxx-");
console.log(result);

If there are always 10 digits, you can use a match followed by a capture group, and then use that capture group in the replacement.

^\d{6}(\d{4})$

Regex demo

const phone = "9871234567"
const result = phone.replace(/^\d{6}(\d{4})$/g, "xxx-xxx-$1");
console.log(result);