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

155
Views
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 answers
Answer question

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 Report

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 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!