Remove all special characters with RegExp

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

As was mentioned in the comments it’s easier to do this as a whitelist – replace the characters which aren’t in your safelist.

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).

Leave a Comment

error code: 523