You can use the Regular expression in replace() method to remove special characters in JavaScript.
var desired = 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
).
JavaScript removes special characters
Simpe example code it will remove only special char (not whitsapce) from string.
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Hello^# World/ &*#special -+characters!~";
var res = str.replace(/[^a-zA-Z ]/g, "");
console.log(res)
</script>
</body>
</html>
Output:
More code
//You can do it specifying the characters you want to remove:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
//Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g, '');
Do comment if you have any doubts or suggestions on this JS code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version