How to remove all non-alphanumeric characters in JavaScript?

Are you struggling with how to remove all non-alphanumeric characters from a string in JavaScript?

Well, keep reading because this article will show you how you can remove it easily and effectively.

Discover an expert approach to effectively remove non-alphanumeric characters in JavaScript with this comprehensive step-by-step guide.

Enhance your web development prowess and elevate the performance of your scripts.

What is non-alphanumeric characters?

Non-alphanumeric characters are those that are not letters or numbers.

They include symbols, punctuation marks, whitespace, and special characters that are not part of the alphabet or numeric system.

Examples of non-alphanumeric characters are “@” symbol, “&”, “$”, “#”, “%”, “*”, “.”, “/”, and many others.

While these characters serve various purposes like formatting or representing special characters, removing them is important when working with alphanumeric data to ensure consistency and compatibility.

How to remove non alphanumeric characters in javascript?

To remove all non-alphanumeric characters from a string in JavaScript, you can use the String.replace() method to get rid of any characters in a string that are not letters or numbers.

Here’s the syntax:

str.replace();

It lets you find and replace specific parts of the string with ease.

Solution 1: Use string.replace()

For example, you can use str.replace(/[^a-z0-9]/gi, ”);.

This method replaces all non-alphanumeric characters in the string with nothing, effectively removing them.

const str = '!It&#source@%code*^(';

const replaced = str.replace(/[^a-z0-9]/gi, '');
console.log(replaced);

We added the “g” flag to match and replace all non-alphanumeric characters, not just the first one.

The “i” flag helps us ignore the difference between uppercase and lowercase letters during the matching process.

Output:

Itsourcecode

On the other hand, you use the following code which also uses the str.replace with call back function.

This solution is similar to the Solution above, but it uses a special function inside the replace() method.

It looks for any characters in the input string that are not letters or numbers (non-alphanumeric).

When a non-alphanumeric character is found, it is replaced with nothing, effectively removing it from the original string.

For example:

const inputString = "Hi, Welcome to @Itsource/code!";
const result = inputString.replace(/[^a-zA-Z0-9]/g, (match) => {
  return '';
});
console.log(result);

Output:

HiWelcometoItsourcecode

You can also use the following code:

const inputString = "Hi, Welcome to @Itsource/code!";
const result = inputString.replace(/[^a-zA-Z0-9]/g, "");
console.log(result);

This solution uses a regular expression /[^a-zA-Z0-9]/g to match any non-alphanumeric character in the input string.

The replace() method is then used to replace all the matched characters with an empty string, effectively removing them from the original string.

Output:

HiWelcometoItsourcecode

Solution 2: : Use the split() and join() methods with regular expressions

This method breaks down the input string into individual characters.

Then, it filters out only the characters that are alphanumeric using a regular expression /[a-zA-Z0-9]/.

Finally, it combines the filtered characters back into a single string.

const inputString = "Hi, Welcome to @Itsource/code!";
const result = inputString.split('').filter(char => /[a-zA-Z0-9]/.test(char)).join('');
console.log(result);

Output:

HiWelcometoItsourcecode

Solution 3: Use the ASCII Codes

In this solution, we use a for loop to examine each character in the input string.

By obtaining the ASCII code of each character using the charCodeAt() method, we determine if it falls within the range of alphanumeric characters.

Only the alphanumeric characters are added to a new string.

For example:

const inputString = "Hi, Welcome to @Itsource/code!";
let result = "";
for (let i = 0; i < inputString.length; i++) {
  const charCode = inputString.charCodeAt(i);
  if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
    result += inputString[i];
  }
}
console.log(result);

Output:

HiWelcometoItsourcecode

Solution 4: Use the \W special character

We can use the regex Metacharacter (\W) to remove all special characters, including spaces, from a string.

For example:

const str = '!It&#source@%code*^(';

const sample = str.replace(/\W/g, "");
console.log(sample);

Output:

Itsourcecode

To make your regular expression shorter and get rid of any non-alphanumeric characters in a string, you can use the special character \W.

Alternatively, you can use the following code, to remove non-alphanumeric characters from a string in JavaScript.

function removeNonAlphanumeric(string) {
  return string.replace(/\W/g, '');
}

console.log(removeNonAlphanumeric('It!(@s#o(u@r$ce/code')); 
console.log(removeNonAlphanumeric('I_T@s#o(*ur*ce(_code!'));

Output:

Itsourcecode
I_Tsource_code

Please be aware that the \W special character does not remove underscores from the string.

Why is it dominant to remove all non-alphanumeric characters in JavaScript?

It’s important to remove non-alphanumeric characters from string in JavaScript for several reasons.

By doing so, we ensure that the information remains consistent and in the desired format.

It also plays a vital role in validating inputs, enhancing security, and improving compatibility across different systems.

Moreover, removing these characters contributes to better readability and a smoother user experience, preventing errors and vulnerabilities in the process.

Conclusion

In conclusion, this article provides simple yet effective solutions for removing non-alphanumeric characters from a string in JavaScript.

By utilizing methods like String.replace(), regular expressions, and ASCII codes, these solutions ensure consistency, compatibility, and security in your code while improving readability and user experience.

We are hoping that this article provides you with enough information that helps you understand the remove non alphanumeric characters in JavaScript.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment