Removing non-alphanumeric chars
The following is the/a correct regex to strip non-alphanumeric chars from an input string:
input.replace(/\W/g, '')
Note that \W
is the equivalent of [^0-9a-zA-Z_]
– it includes the underscore character. To also remove underscores use e.g.:
input.replace(/[^0-9a-z]/gi, '')
The input is malformed
Since the test string contains various escaped chars, which are not alphanumeric, it will remove them.
A backslash in the string needs escaping if it’s to be taken literally:
"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')
"testredbobfrednew" // output
Handling malformed strings
If you’re not able to escape the input string correctly (why not?), or it’s coming from some kind of untrusted/misconfigured source – you can do something like this:
JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')
"testredbobfrednew" // output
Note that the json representation of a string includes the quotes:
JSON.stringify("\\test\red\bob\fred\new")
""\\test\red\bob\fred\new""
But they are also removed by the replacement regex.