How to Remove Non-Alphanumeric Characters From a String in JavaScript

Here are two ways to remove all the non-alphanumeric characters from a string.

  1. Using string.replace() with regular expression
  2. Using for loop

Method 1: Using the str.replace() function

The str.replace() method is “used to search and replace specified substrings or patterns within a string.”

Syntax

str.replace();

Return value

This method returns a new string with all matches replaced.

Example

const str = 'jo@#*hn'


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


console.log(replaced);

Output

john

Method 2: Using for loop

You can use a for loop to iterate through each character in a string and check if it’s alphanumeric. If it is, you can add it to a new string. This method is straightforward and can be used in many programming languages, including JavaScript.

Example

function removeNonAlphanumeric(str) {
  let result = '';
  for (let i = 0; i < str.length; i++) {
    if ((str[i] >= 'a' && str[i] <= 'z') ||
        (str[i] >= 'A' && str[i] <= 'Z') ||
        (str[i] >= '0' && str[i] <= '9')) {
          result += str[i];
    }
 }
 return result;
}

console.log(removeNonAlphanumeric("Hello, World!123"));

Output

HelloWorld123

That’s it.

Leave a Comment