DEV Community

Discussion on: Daily Challenge #179 - Hide Phone Numbers

Collapse
 
alvaromontoro profile image
Alvaro Montoro

JavaScript

If we want all the phone numbers to have the same format, we could use a regular expression to detect all the digits (assuming that the phone number is correct) and format it accordingly:

const encryptNum = (num) => {
  const nums = num.match(/\d/gi).join("");
  return `${nums.substring(0,3)}-${nums.substring(3,6)}-${nums.substring(6)}`;
}

If we want to keep the original format (and again, assuming the phone number is correct), another solution would be transforming the string into an array (strings are immutable, an array would be easier to operate), parse the last 6 digits and return its concatenation:

const encryptNum = (num) => {
  let numbers = 0;
  let position = num.length - 1;
  let formattedNum = num.split("");

  while (numbers < 6 && position > 0) {
    if (num[position] >= "0" && num[position] <= "9") { 
      formattedNum[position] = "x";
      numbers++;
    }
    position--;
  }

  return formattedNum.join("");
}