skip to Main Content

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


  1. 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)}`)
    Login or Signup to reply.
  2. 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);
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search