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

157
Vistas
add character inside string using on keyup regex javascript

i create function using event on key up to put "/" inside value from input user using regex but still bug, can someone help me ?

$('#validUntil').on('keyup', function(e){

                    $(this).val(function(index, value) {
                        return value
                        // Add "/" separators:
                        .replace(/\B(?=(\d{2})+(?!\d))/g, "/")
                    });
});

for example if i typing 5121 the result must be 51/21. the problem is that the results do not match, the displayed results are : 5/1/21

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

0

Welcome to Stack Overflow. Consider the following.

$(function() {
  $('#validUntil').on('keyup', function(e) {
    var val = $(this).val();
    if (val.length > 3) {
      $(this).val(val.replace(/\B(?=(\d{2})+(?!\d))/g, "/"));
    }
    return true;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="validUntil" />

I suspect the primary issue is that the value is assessed on each keyup event.

Adding a condition to ensure a proper length will help ensure the regex works when it is needed.

Now if the User enters 512111 you will get similar issues. So maybe if / is detected, it is remove and then the regex replacement is applied.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You're adding a slash before the last two numbers in the input, every time its value updates.

So when you are typing:


5 => 5

5 + 1 => 51 => 51

51 + 2 => 512 => 5/12

5/12 + 1 => 5/121 => 5/1/21


When inserting the slash, make sure to remove the previously inserted slash:

return value.replaceAll('/', '')
            .replace(/\B(?=(\d{2})+(?!\d))/g, "/")
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