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
).
Source: stackoverflow.com
Example Replace all special characters in JavaScript
A simple example code uses a regular expression to replace
them with the empty string.
<!doctype html>
<head>
<script>
var s = "img_realt@ime_tr~ading3$";
var res = s.replace(/[^\w\s]/gi, '')
console.log(res)
</script>
</head>
<body>
</body>
</html>
Output:
![Replace all special characters in JavaScript](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2022/01/Replace-all-special-characters-in-JavaScript.jpg?resize=212%2C67&ssl=1)
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