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

Many times, when you create and host your website, you add input fields in it in order to get input from users. For example, during the signup process, you may require your user to enter their first name, last name, email address, and desired password.  Like in the case of signup pages, you require your users to enter their first name but the first name cannot contain non-alphanumeric characters so you have to remove non-alphanumeric characters from the string if the user entered. In this post, we will discuss how we can remove non-alphanumeric characters from a string in JavaScript.

Remove Non-Alphanumeric Characters From a String in JavaScript

To remove all the non-alphanumeric characters from a string,  call a built-in method which is “str. replace()”. In str. replace() method, you have to pass 2 arguments(pass the regex expression in 1st argument and pass an empty string ‘ ‘ as the second argument).

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

Explanation

  • First, create a variable and store a string in it.
  • Then called the replace method on that variable.
  • We have to pass two parameters in replace() method. The first parameter is the regular expressions, and the second parameter is the replacement for each match. In our case, we have passed an empty string because we have to remove all non-alphanumeric characters.
  • You can see the replaced contains a new string with all the non-alphanumeric characters removed.

Note

The forward slashes / / indicates the beginning and end of the regular expression.

Conclusion

So in this post, we discussed how to remove Non-Alphanumeric characters from a string in JavaScript. You can use replace() method to remove all non-alphanumeric characters from the string. I hope that this content was informative for you and that you found this post helpful.

Leave a Comment