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
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
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, '')">
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,'')">
The inline event listeners are considered bad practice and you should probably do it in the JS land using addEventListener
.
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">