You should use the string replace function, with a single regex. Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from Petar Ivanov on Stack OverflowYou should use the string replace function, with a single regex. Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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, '');
Removing special characters from a string
javascript - Regular expression - replace special characters, except dot - Stack Overflow
javascript - Regex remove all special characters except numbers? - Stack Overflow
Removing Special Characters Using an Built In Function | OutSystems
Use this for the regex instead:
/[^\w.]|_/g
It reads any character that is not either alpha-numerical (which includes underbars) or dot, or that is an under bar.
update
But this is perhaps little more readable:
/[^0-9a-zA-Z.]/g
It's a bit old now but in case someone still need it, Faust's answer didn't work for me (I tried to change a file's name to use it in a URL) so here's the solution I found :
preg_replace('/[^A-Za-z0-9.\-]/', '', $string);