Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

491
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda