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

478
Views
Regex - How to replace a specific character in a string after being typed only once?

I'm trying to limit an input field to only numbers and the possibility of a "+" sign just at the string's [0] index. The idea is to let the user type their phone number, I have come up with this:

function main() {
  let phone = document.getElementById('phone');
  let phoneRegex = /[a-zA-Z]|[-!$%^&*()_|~=`{}[\]:";'<>?,./]/;
  phone.value = phone.value.replace(phoneRegex, '');

  console.log(phone.value);
}
<input id="phone">
<button onclick="main()">Run</button>

The thing is, this works fine, but I want to limit the first character to only a digit or a "+" sign, characters coming from index [1] and on should only be numbers.

I can't come up with an idea on how to solve this

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

0

Try this as a starting point (you'll probably want to expand it further to account for total string length, delimiters like -, etc.):

let phoneRegex = /\+?\d+/;

+ in a regular expression has a special meaning, so when we want to match the literal character "+" then we need to escape it. And following it with the ? character makes it optional:

\+?

Next, \d followed by + will match any sequence of one or more digits:

\d+

You can see a visualization of this pattern here.

about 4 years ago · Juan Pablo Isaza Report

0

I know I'm late in this game, but adding one more solution for me and other's future references.

I came up with this solution which works for me:

/^(\+|[0-9])?[0-9]{12}$/

Thanks

about 4 years ago · Juan Pablo Isaza Report

0

I want to limit the first character to only a digit or a "+" sign, characters coming from index [1] and on should only be numbers.

The regex:

/^\+?\d+$/

means:

From the beginning, one or zero + signs, then one or more numbers until the end.

Note the following regex symbols:

  • * - zero or more
  • + - one or more
  • ? - zero or one
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!