admin管理员组

文章数量:1356815

I want to strip invalid characters from a string with js.

My regex currently is as below:

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

i.e find anything but a-z or 0-9 and spaces independent of casing and replace with nothing - however I also want to allow underscore (_), hyphen (-) and dot (.).

I attempted to update my regex as below but it is not working as expected - after I made the change I found strings with brackets () were not getting those stripped?

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

Am I missing something simple?

I want to strip invalid characters from a string with js.

My regex currently is as below:

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

i.e find anything but a-z or 0-9 and spaces independent of casing and replace with nothing - however I also want to allow underscore (_), hyphen (-) and dot (.).

I attempted to update my regex as below but it is not working as expected - after I made the change I found strings with brackets () were not getting those stripped?

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

Am I missing something simple?

Share Improve this question edited May 6, 2015 at 11:44 collapsar 17.3k5 gold badges40 silver badges65 bronze badges asked May 6, 2015 at 11:40 Ctrl_Alt_DefeatCtrl_Alt_Defeat 4,00913 gold badges70 silver badges125 bronze badges 2
  • I always use regex 101 to test any assumptions. See the link below. I've made it multi-line for the sake of the example regex101./r/xY1aL3/1 – benembery Commented May 6, 2015 at 12:02
  • @benembery - thanks for the link - really useful - never came across it before – Ctrl_Alt_Defeat Commented May 6, 2015 at 12:08
Add a ment  | 

4 Answers 4

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

                                               ^^

Keep - at the end as it forms a range when placed between []. Now it is forming a range between . and _. Or you can escape it as well.

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

You have to escape a dot and hyphen:

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

Use backslash to escape . - _

this should work

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

ALSO... you can also use \w to represent letters numbers and undrescore

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

Put the literal dash last in the character class, or escape it with a backslash. Right now it's allowing an ASCII range of . to _.

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

Side note: you don't need the parenthesis unless you're storing the match for something (and if parenthesis cover the whole match you don't need them then either, because \0 refers to the entire match).

本文标签: Javascript regex for cleaning string valueStack Overflow