Replace all special characters in JavaScript | Example code

  • by

Use replace method with a regular expression to Replace all special characters in JavaScript.

stringToReplace.replace(/[^\w\s]/gi, '')

The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).


Example Replace all special characters in JavaScript

Simple example code uses a regular expression to replace them with the empty string.

<!doctype html>

      var s = "[email protected]_tr~ading3$";
      var res = s.replace(/[^\w\s]/gi, '')





Replace all special characters in JavaScript

Remove all special characters except space from a string using JavaScript

const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));

Output: abcs tests

Do comment if you have any doubts or suggestions on this JS replace code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.