I like the solution povided by "Remove not alphanumeric characters from string. Having trouble with the [\] character" but how would I do this while leaving the spaces in place?
I need to tokenize string based on the spaces after it has been cleaned.
A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string. You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] .
To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.
input.replace(/[^\w\s]/gi, '')
Shamelessly stolen from the other answer. ^
in the character class means "not." So this is "not" \w
(equivalent to \W
) and not \s
, which is space characters (spaces, tabs, etc.) You can just use the literal if you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With