-1

I am trying to remove special character like @,#, etc. except space with null string

<input type='text' onkeyup="this.value.replace('/[^a-zA-Z0-9]/g', '')">

But it's not working

vivek modi
  • 800
  • 2
  • 7
  • 23

3 Answers3

1

You need to remove quotes around regex pattern and also assign replaced value to this.value because replace method creates a new string, it doesn't modify the string you're operating on

<input type='text' onkeyup="this.value = this.value.replace(/[^a-zA-Z0-9]/g, '')">
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

Changing the value that way doesn't replace the original value. It gives you a new string instead. Once you do the replacement, you have to assign it back to this.value and that should do the trick.

Also, regex pattern doesn't need to be in quotes. It starts and ends with '/'. So you have to remove that.

More Read - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

<input type='text' onkeyup="this.value = this.value.replace(/[^a-zA-Z0-9]/g,'')">

Suggestion

The inline event listeners are considered bad practice and you should probably do it in the JS land using addEventListener.

Praveen Puglia
  • 5,577
  • 5
  • 34
  • 68
0

It's generally not a good idea to use inline event handlers. Alternative: use the input event and a delegated handler for it:

{
  document.addEventListener("input", textOnly, true);
  
  function textOnly(evt) {
    const origin = evt.target;
    if (origin.id === "textOnly") {
      origin.value = origin.value
        .replace(/[^a-z0-9]$/i, "");
      //                   ^ only the last inputted character
    }
  }
}
<input type="text" id="textOnly">
KooiInc
  • 119,216
  • 31
  • 141
  • 177