With JavaScript I would like to remove all characters from a string which are not numbers, letters and whitespace. So remove characters like '%#$&@*
so something like:
Player's got to * play! #justsaying
would become:
Players got to play justsaying
How can I do this, I'm not sure about regex.
To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.
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] .
Using Split() with Join() method To remove all whitespace characters from the string, use \s instead. That's all about removing all whitespace from a string in JavaScript.
As @chris85 said, you can use the regular expression [^0-9a-z-A-Z]
to replace all the characters that are not letters, numbers, or whitespace.
Here is a function that will do what you want:
function clean(str) {
return str.replace(/[^0-9a-z-A-Z ]/g, "").replace(/ +/, " ")
}
The second replace call is needed to remove the runs of extra whitespace that are made from removing a character that is between spaces.
Use replace
string.replace(/[^A-Z\d\s]/gi, '')
Note the two flags at the end of the regex
g
- stands for global, and means that every such instance of the regular expression will be found
i
- stands for case insensitive. That means it will match both lower case and uppercase characters
Playing with your string, it returns this output
"Players got to play justsaying"
To transform two or more whitespace characters into a single whitespace, you could hain another replace
method to the existing ones.
string.replace(/[^A-Z\d\s]/gi, '').replace(/\s+/g, ' ')
The key here is the +
character, which finds one or more.
It's probably possible to do it more efficiently, but I'm an amateur in Regex.
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