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
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).
source to share