js remove nonalphanumeric

How to Remove Non-Alphanumeric Characters in JavaScript

As a web developer, I have often come across situations where I need to remove non-alphanumeric characters from a string in JavaScript. This can be useful when working with user input, parsing data, or cleaning up URLs.

Using Regular Expressions

One way to remove non-alphanumeric characters is to use regular expressions. Regular expressions are patterns used to match character combinations in strings. In JavaScript, you can use the replace() method with a regular expression to replace non-alphanumeric characters with an empty string.

let str = "Hello! How are you?";

let cleanedStr = str.replace(/[^a-z0-9]/gi, "");

console.log(cleanedStr); // Output: HelloHowareyou
  • /[^a-z0-9]/gi: This regular expression matches any character that is not a letter or a number. The g and i flags mean that the matching should be global (i.e., all occurrences) and case-insensitive, respectively.
  • "": This is the replacement string, which is empty in our case. This means that any non-alphanumeric characters will be removed.

The above code will remove all non-alphanumeric characters from the string "Hello! How are you?" and return "HelloHowareyou".

Using ASCII Table Values

Another way to remove non-alphanumeric characters is to loop through the string and check each character's ASCII value. Alphanumeric characters have ASCII values between 48 and 57 (for 0-9), 65 and 90 (for A-Z), and 97 and 122 (for a-z).

function removeNonAlphaNumeric(str) {
  let cleanedStr = "";

  for (let i = 0; i < str.length; i++) {
    let charCode = str.charCodeAt(i);

    if (
      (charCode > 47 && charCode < 58) || // 0-9
      (charCode > 64 && charCode < 91) || // A-Z
      (charCode > 96 && charCode < 123)   // a-z
    ) {
      cleanedStr += str[i];
    }
  }

  return cleanedStr;
}

let str = "Hello! How are you?";

console.log(removeNonAlphaNumeric(str)); // Output: HelloHowareyou

The above code defines a function removeNonAlphaNumeric() that takes a string as input and returns the cleaned string. The function loops through each character in the string, checks its ASCII value, and adds it to the cleaned string only if it is alphanumeric.

The output of the above code will also be "HelloHowareyou".

Conclusion

These are two ways to remove non-alphanumeric characters from a string in JavaScript. Regular expressions offer a more concise and elegant solution, while looping through the string and checking ASCII values may be more readable for some developers.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe