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
4 Answers
Reset to default 8var 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
版权声明:本文标题:Javascript regex for cleaning string value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744072804a2586194.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论