Phone number input mask in JS

Viewed 134

I'm trying to figure out where the number 1 comes from (in the example below you write any phone number and press Backspace many times). Can you please tell me what is wrong in this code?

const input = document.querySelector('input[name="phone"]');

input.addEventListener('input', function () {
  let x = input.value;
  x = x.replace(/^\+1 /, '');
  x = x.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
  x = !x[2] ? x[1] : x[1] + ' ' + x[2] + (x[3] ? `-${x[3]}` : '') + (x[4] ? `-${x[4]}` : '');
  x = x.startsWith('+1 ') ? x : '+1 ' + x;
  input.value = x;
});
<input name="phone" placeholder="Phone number">

2 Answers

You need remove it on your code.

phone = phone.replace(/^\+1 /, '')

Also:

phone = phone.startsWith('+1 ') ? phone : '+1 ' + phone;

You had to replace the line:

x = x.replace(/^\+1 /, '');

to:

x = x.replace(/^\+1/, '');

(remove the space)

Related