Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript remove all characters from string which are not numbers, letters and whitespace

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.

like image 925
Holly Avatar asked Jan 13 '17 15:01

Holly


People also ask

How do I remove all characters from a string except numbers?

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.

How do you remove non 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 get rid of all whitespace in a string JavaScript?

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.


2 Answers

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.

like image 88
BookOwl Avatar answered Oct 08 '22 08:10

BookOwl


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.

like image 21
Richard Hamilton Avatar answered Oct 08 '22 09:10

Richard Hamilton