Remove all special characters except space from a string using JavaScript

nithi picture nithi · Jul 2, 2011 · Viewed 405.6k times · Source

I want to remove all special characters except space from a string using JavaScript.

For example, abc's test#s should output as abcs tests.

Answer

Petar Ivanov picture Petar Ivanov · Jul 2, 2011

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, ""));