0
<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.

1
  • Well is 12,b2a an allowed input, given that it contains letters? Commented Dec 10, 2022 at 8:34

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

2 Comments

i think so that but if you ented another languege, it's not woking. E.g Korean
Sorry, I didn't take that into account. The answer with the ^ mark should do the trick then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.