Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda