In JavaScript, we can remove all non-alphanumeric characters from a string easily by making use of the JavaScript String replace() method and a regex expression.
var someString = "!This is $a )string_with Non-Alphanumeric characters@";
someString = someString.replace(/[^0-9a-z]/gi, '');
console.log(someString);
#Output:
ThisisastringwithNonAlphanumericcharacters
Notice in the replace method above, that instead of using .replace("/[^0-9a-z]/", '')
we use replace(/[^0-9a-z]/gi, '')
. If we used the expression "/[^0-9a-z]/"
in the replace function, it would only replace the FIRST instance of a non-alphanumeric character. Using the regular expression /[^0-9a-z]/gi
makes it so we replace ALL instances of a non-alphanumeric character in the string.
When using string variables in JavaScript, we can easily perform string manipulation to change the value of the string variables.
One such manipulation is to remove characters from a string variable. Non-alphanumeric characters can be troubling characters to deal with in string variables.
We can easily remove non-alphanumeric characters from a string in JavaScript.
The easiest way to get rid of a non-alphanumeric character in a string using JavaScript is with the JavaScript String replace() function.
The replace() function takes two arguments: the substring we want to replace, and the replacement substring. In this case, to remove non-alphanumeric characters, we pass the regex for non-alphanumeric characters (“[^0-9a-z]”) as the first argument and an empty string as the second argument.
Below is our example again of how you can remove non-alphanumeric characters from strings in JavaScript using the replace() function.
var someString = "!This is $a )string_with Non-Alphanumeric characters@";
someString = someString.replace(/[^0-9a-z]/gi, '');
console.log(someString);
#Output:
ThisisastringwithNonAlphanumericcharacters
Hopefully this article has been useful for you to learn how to use JavaScript to remove all non-alphanumeric characters from a string.