We will use the regular expression method to remove all non-alphanumeric characters from a string. A regular expression is an object that describes a pattern of characters.
For instance, the regular expression \s matches any white space character, including space, tab, form feed, and new line.
The regular expression /\s+/ matches one or more white space characters.
The replace() method searches a string for a specified value and replaces it with another value.
let str = "abcdef!@#$%^&*()_+"; console.log(str.replace(/\W/g, '')); // "abcdef"</p><br /><h2>Use a Regular Expression</h2><br /><p> To remove all nonalphanumeric characters from a string, you can use the `replace()` method with a regular expression. The regular expression will remove all characters that are not alphanumeric or a space. This includes punctuation, symbols, and whitespace. The `replace()` method will return a new string with the replaced character.</p><br /><h3>Use the replace() function</h3><br /><p>
var myString = "This is a test string!"; var newString = myString.replace(/[^a-z0-9]/gi,''); // newString will now be "Thisisateststring"</p><br /><h3>Use a RegExp object</h3><br /><p>
g – global match
i – ignore case
m – multiline match
y – sticky match
The flags can be used independently or together in any order. For example, /ab/gi would be the same as /(?:ab)/gi. The only exception is the y flag, which cannot be used with the g flag.
Use the String.prototype.match() method
The String.prototype.match() method is used to retrieve the matches when matching a string against a regular expression.
Use the String.prototype.replace() method
You can use the replace() method to replace all non-alphanumeric characters with an empty string.
For instance, given the following string:
var str = “Hello!+*”;
You can remove all non-alphanumeric characters from it like so:
str.replace(/[^a-z0-9]/gi, ”); // “Hello”
return str.replace(/[^a-zA-Z0-9]/g, “”);