To remove all the non-alphanumeric characters from a string, call a built-in method which is “str. replace()”. In str. replace() method, you have to pass 2 arguments(pass the regex expression in 1st argument and pass an empty string ‘ ‘ as the second argument).
This method returns a new string with all matches replaced.
const str = 'jo@#*hn' const replaced = str.replace(/[^a-z0-9]/gi, ''); console.log(replaced);
- First, create a variable and store a string in it.
- Then called the replace method on that variable.
- We have to pass two parameters in replace() method. The first parameter is the regular expressions, and the second parameter is the replacement for each match. In our case, we have passed an empty string because we have to remove all non-alphanumeric characters.
- You can see the replaced contains a new string with all the non-alphanumeric characters removed.
The forward slashes / / indicates the beginning and end of the regular expression.