Phone number masking with brakcets or special characters

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-');

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.