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
2
Answers
Regex is not necessary for this problem. Using
slice
would be much simpler, just get the last 4 digitsInspired 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.
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.