Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all characters except alphanumeric and spaces with javascript

Tags:

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.

like image 884
Aaron Avatar asked Feb 01 '13 05:02

Aaron


People also ask

How do you remove everything except alphanumeric characters from a string?

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

How do you remove non-alphanumeric characters?

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.


Video Answer


1 Answers

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.

like image 151
Explosion Pills Avatar answered Oct 04 '22 00:10

Explosion Pills