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

169
Vistas
Formatting input field phone number with EventListener keyup

I'm working on a form where I need the phone number field to reformat, as you type, into
xxx-xxx xx xx.
This in itself is straight forward and has been asked before but my problem is a bit different:

I've used the JavaScript only approach found in this fiddle, but to adjust to my wanted format I've edited the last code block into this:

const areacode = input.substring(0,3);
const gr1 = input.substring(3,6);
const gr2 = input.substring(6,8);
const gr3 = input.substring(8,10);

if(input.length > 7) {
      target.value = `${areacode}-${gr1} ${gr2} ${gr3}`;
    } else if(input.length > 5) {
      target.value = `${areacode}-${gr1} ${gr2}`;
    } else if(input.length > 2) {
      target.value = `${areacode}-${gr1}`;
    } else if(input.length > 0) {
      target.value = `${areacode}`;
    }

When I try this out in the fiddle, or paste in codepen for example, it works perfectly. But when I apply it to my site, it doesn't. The characters are replaced in a weird manner.


Suspicion: There's a constant containing a regex replace, like so:

const input = event.target.value.replace(/\D/g,'').substring(0,10);

I'm not good with RegEx but as this works in one place but not the other I feel I have to suspect this line of code.


about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Experimenting with the code you provided in the question, I found that it works correctly indeed. Please don't post working code on StackOverflow asking what is wrong with it.

Nevertheless, I examined your website with a debugger and found an issue with the regex: Instead of using input.replace(/\D/g, ""), you wrote input.replace(/D/g, ""), which removes all D characters.

As a side note, I can highly recommend setting breakpoints in the browser source view to solve such problems.

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