Home > Net >  add character inside string using on keyup regex javascript
add character inside string using on keyup regex javascript

Time:12-31

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

CodePudding user response:

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.

CodePudding user response:

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, "/")
  • Related