Javascript regex to clear string value

I want to remove invalid characters from a string using js.

Currently my regex looks like this:

var newString = oldString.replace(/([^a-z0-9 ]+)/gi, '');


those. find anything other than az or 0-9 and shell-independent spaces and replace them with nothing - however I also want to allow underscore ( _

), hyphen ( -

), and period ( .


I tried to update my regex as below, but it doesn't work as expected. After I made the change, I found that lines with brackets () don't get those sections?

var newString = oldString.replace(/([^a-z0-9 .-_]+)/gi, '');


Am I missing something simple?


source to share

4 answers

var newString = oldString.replace(/([^a-z0-9 ._-]+)/gi, '');



Continue -

at the end as it forms a range when placed in between []

. It now forms a range between .

and _

. Or you can avoid it as well.

 var newString = oldString.replace(/([^a-z0-9 ._\-]+)/gi, '');




You need to escape the period and hyphen:

var newString = oldString.replace(/([^a-z0-9 \.\-_]+)/gi, '');




Put the literal slash last in the character class, or remove it with a backslash. This now allows the ASCII range from .

to _


var newString = oldString.replace(/[^a-z0-9 ._-]+/gi, '');


Side note: you don't need the parenthesis unless you are storing the match for something (and if the parentheses span the entire match, in which you don't need them either, because it \0

refers to the entire match).



Use backslash to exit. - _

this should work

.replace(/([^a-z0-9 \.\_\-]+)/gi, '');


ALSO ... you can also use \ w to denote letter numbers and undrescore

[a-zA-Z0-9_] == \w




All Articles