Phone Number Masking with brackets or special characters present

101 Views Asked by At

I am trying to replace the below string like below:

Some of the cases I am considering are:

//Ignore Special char
phone = "+1-555-555-1234"
result = xxx-xxx-1234

phone = "1(800)555-0199"
result = xxx-xxx-0199

//Ignore Space
phone="555 555 1234"
result = xxx-xxx-1234

//if length >10 so only consider the last 10 digit
phone = "9898871234567" //only  consider 8871234567
result = xxx-xxx-4567

//If phone number contains spaces,parenthesis or some garbage character only consider digits.
phone = "9898871234567)"
result = xxx-xxx-4567

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

var lastphdigit = phone.replace(/\d{3}(?!\d?$)/g, 'xxx-');
1

There are 1 best solutions below

1
Robby Cornelissen On

All of your test cases would be satisfied by just appending the last 4 characters of the input to xxx-xxx-:

const format = (phone) => `xxx-xxx-${phone.slice(-4)}`;

console.log(format("+1-555-555-1234")); // xxx-xxx-1234
console.log(format("1(800)555-0199"));// xxx-xxx-0199
console.log(format("555 555 1234")); // xxx-xxx-1234
console.log(format("9898871234567")); // xxx-xxx-4567

So either there are additional cases you would like to see addressed and you need to add those to the question, or you're over-complicating things.