Q: Remove or replace +1 from the string : JavaScript I am applying phone number masking on a phone number. I want to make sure that there is no +1 in the beginning and if there is remove it. What would be the best way to do that?


self.phoneNumberMasking = function (data) {
        if (data != "" && data != null) {
            var x = data.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
            data = '+1(' + x[1] + ')' + x[2] + '-' + x[3];
            return data;
        }
        return data;
    }


Since I am not removing or replacing +1 in the above code, it is adding another 1 when I try to apply the mask on a number that already has +1 in it.

A: You do not need to use replace() you just need a better regex like
/(\d{3})\D*(\d{3})\D*(\d{4})$/
This will ignore the '+1' at the beginning due to the $ it basically captures only the last 10 digits (in the proper grouping).
A good tool to use for debugging is regex101.


let phoneNumberMasking = function(data) {
  if (data != "" && data != null) {
    var x = data.match(/(\d{3})\D*(\d{3})\D*(\d{4})$/);
    data = '+1(' + x[1] + ')' + x[2] + '-' + x[3];
    return data;
  }
  return data;
}
console.log(phoneNumberMasking('2345678910'))
console.log(phoneNumberMasking('+1(234) 567 - 8910'))
console.log(phoneNumberMasking('+1-234-567-8910'))
console.log(phoneNumberMasking('area code:[234] phone number: 567_8910'))



A: Modified your 'replace regex' to also replace the "+1" from the beginning of the string.
Please check.
self.phoneNumberMasking = function (data) {
        if (data != "" && data != null) {
         
            // var x = data.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
        
            var x = data.replace(/(^\+1|\D)/g, '').match(/(\d{3})(\d{3})(\d{4})/);
            data = '+1(' + x[1] + ')' + x[2] + '-' + x[3];
            return data;
        }
        return data;
    }


A: You can use String.prototype.startsWith() to check if the input starts with "+1", and, if so, remove it before further processing:


function validate (input) {
  let str = input.trim();
  if (str.startsWith('+1')) str = str.slice(2);
  str = str.replaceAll(/\D/g, '');
  if (str.length !== 10) throw new Error('Invalid input');
  return `+1(${str.slice(0, 3)})${str.slice(3, 6)}-${str.slice(6)}`;
}

const inputs = [
  '+11234567890',
  '1234567890',
  '+1 123.456.7890',
  '+1 123 456 7890',
  '1 123 456 7890',
];

for (const input of inputs) {
  try {
    const result = validate(input);
    console.log(input, result);
  }
  catch (err) {
    console.error(input, err.message);
  }
}


