This website collects cookies to deliver better user experience
How to remove all the non-alphanumeric characters from a string using JavaScript?
How to remove all the non-alphanumeric characters from a string using JavaScript?
To remove all the non-alphanumeric characters from a string, we can use a regex expression that matches all the characters except a number or an alphabet in JavaScript.
TL;DR
// a stringconst str ="#HelloWorld123$%";// regex expression to match all// non-alphanumeric characters in stringconst regex =/[^A-Za-z0-9]/g;// use replace() method to// match and remove all the// non-alphanumeric charactersconst newStr = str.replace(regex,"");console.log(newStr);// HelloWorld123
For example, lets' say we have a string like this #HelloWorld123$%,
// a stringconst str ="#HelloWorld123$%";
As we can see from the above string there are some characters like #$% which is not a number or an alphabet. So here we can define a regex expression to first match all the non-alphanumeric characters in the string.
It can be done like this,
// a stringconst str ="#HelloWorld123$%";// regex expression to match all// non-alphanumeric characters in stringconst regex =/[^A-Za-z0-9]/g;
Now we can use the replace() string method and :
pass the regex expression as the first argument to the method
and also pass an empty string '' as the second argument to the method
the method returns a new string
This will remove all the non-alphanumeric characters from the string and replaces it with an empty string.
It can be done like this,
// a stringconst str ="#HelloWorld123$%";// regex expression to match all// non-alphanumeric characters in stringconst regex =/[^A-Za-z0-9]/g;// use replace() method to// match and remove all the// non-alphanumeric charactersconst newStr = str.replace(regex,"");console.log(newStr);// HelloWorld123
As you can see the newStr contains a new string with all the non-alphanumeric characters removed.