Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Phone number input mask in JS

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">

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You need remove it on your code.

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

Also:

phone = phone.startsWith('+1 ') ? phone : '+1 ' + phone;
about 4 years ago · Juan Pablo Isaza Report

0

You had to replace the line:

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

to:

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

(remove the space)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!