Search code examples
javascriptmasking

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.


Solution

  • 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);
      }
    }