How to Remove all non-alphanumeric Characters from String in JS

How to Remove all non-alphanumeric Characters from String

Are you having trouble and don’t know how to remove all non-alphanumeric characters from string in JS? If yes, let’s follow this article. It’s helpful for you.

Now, let’s start searching and removing special characters other than letters and numbers in the string using JS language.

The search “replace()” method returns a new string with one, some, or all matches.

Remove all non-alphanumeric Characters from String in JS

Case 1: Remove non-alphanumeric characters from a string

We start with a simple example as follows.

Code sample:

const str = 'Hello [email protected]#$(Guy)%^* 123'; // Input string
const str_replaced = str.replace(/[^a-z0-9]/gi, ''); 
console.log(str_replaced);

In the first line we will pass in a string consisting of special characters, letters, numbers, and spaces.

In the second line, we will pass the parameters to the “str.replace()” method : 

  • With a regular expression that we want to match in the string.
  • Substitutions for each match. For our purposes, an empty string because we want to remove all non-alphanumeric characters.

Note:

The slash “//” marks the beginning and the end of the regular expression.

The square bracket “[]” is called a character class.

The caret symbol “^” means match the beginning of the input. If the multiline flag is set to true, also match immediately after the line break character.

Here we have used the “g” (global) flag to compare all occurrences of non-alphanumeric characters, not just the first occurrence.

And use the “i” flag to be case-insensitive by targeting all uppercase and lowercase characters.

Output:

HelloGuy123

So we have returned a new string containing alphanumeric characters, and special characters and spaces have also been removed.

Case 2: Remove non-alphanumeric characters from a string, but retains empty characters.

Let’s continue with the above example.

But for this case we will have a little change to the parameters in the second line of code.

We will add the space parameter to the “str.replace()” method

with specific parameters “str.replace(/[^a-z0-9 -]/gi, '')“.

Code sample:

const str = 'Hello [email protected]#$(Guy)%^* 123';
const Str_replaced = str.replace(/[^a-z0-9 -]/gi, '');
console.log(Str_replaced);

Output:

Hello Guy 123

Thus, we have removed the set characters that are not letters, numbers but still keep the empty characters in the string.

Summary

Through the above 2 simple cases, we can easily remove special characters, or unwanted characters from the string. Thank you for reviewing my article.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *