Remove Non Alphanumeric in Javascript

In this post, We learn how to remove Non-alphanumeric characters from a string in javascript.

What are non alphanumeric characters?

Non-alphanumeric characters are those characters or kinds of symbols. Such as exclamation mark(!), at symbol(@), commas(, ), question mark(?), colon(:), dash(-) etc and special characters like dollar sign($), equal symbol(=), plus sign(+), apostrophes(‘).

1. Using \w Metacharacter

In the first method use \w Metacharacter. The RegExp \W Metacharacter in JavaScript is used to find the non-word character.

const str = "#Coder$^$%[email protected]$^&&**)(**%";


// use replace() method to match 
// and remove all the non-alphanumeric characters

const newStr = str.replace(/\W/g, "");
// \W Metacharacter expression to match 
//all non-alphanumeric characters in string


console.log(newStr); // CodeMen

2. Using Regex Expression

In the second method, we use regex expression to match all non-alphanumeric characters.

// a string
const str = "#Coder$%^$%$&Men";

// regex expression to match all
// non-alphanumeric characters in string
const regex = /[^A-Za-z0-9]/g;

// use replace() method to
// match and remove all the
// non-alphanumeric characters
const newStr = str.replace(regex, "");

console.log(newStr); // CoderMen

So here As you can see the newStr variable contains a new string with all the non-alphanumeric characters removed.

Thanks