Home > database >  How to remove characters when input not matches regex in JS
How to remove characters when input not matches regex in JS

Time:12-10

<input id="myInput" onblur="myFunction()">

<script>
    function myFunction() {
      var value= document.getElementById('myInput').value;
      var regexCharacter = /[0-9|,] /g;
      strFirst = value.replace(regexCharacter, '')
      document.getElementById('myInput').value = strFirst
    }
</script>

I want to replace '' when the input does not match the regex's. My regex just allow input number and comma. My function is replace when input matching, i want to replace when it's not matching. E.g a12,b2a => 12,2 can anyone help me, thanks.

CodePudding user response:

I think you should edit your regex to match letters instead of numbers. Like this: /[a-zA-Z|] /g

CodePudding user response:

Use /[^0-9|,] /g as your regex. The ^ mark is used to match any character that's not in range.

Pro tip: You dont have to memorize all these tokens, just use a tool like https://regex101.com/

CodePudding user response:

First of all, your function is not called to check the value with reqex. then yout reqex replace "" when is number not charactors

<input type="text" id="myInput">

<script>
    myInput.addEventListener("input", function (e) {
      var value= document.getElementById('myInput').value;
      strFirst = value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')
      document.getElementById('myInput').value = strFirst
    });
</script>

in this code you can write number whith dot whith this reqex

value.replace(/[^0-9.]/g, '').replace(/(..?)../g

  • Related