How to remove all the non-alphanumeric characters from a string using JavaScript?

June 23, 2021 - 2 min read

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 string
const str = "#HelloWorld123$%";

// 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); // HelloWorld123

For example, lets' say we have a string like this #HelloWorld123$%,

// a string
const 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 string
const str = "#HelloWorld123$%";

// regex expression to match all
// non-alphanumeric characters in string
const 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 string
const str = "#HelloWorld123$%";

// 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); // HelloWorld123

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

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.