DEV Community

loading...
Cover image for 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?

MELVIN GEORGE
Hi, I'm Melvin George, A web developer, and a blogger.
Originally published at melvingeorge.me ・2 min read

Originally posted here!

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
Enter fullscreen mode Exit fullscreen mode

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

// a string
const str = "#HelloWorld123$%";
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 πŸ˜ƒ.


Discussion (0)