Javascript Regex指定允许的内容(而不是不允许的内容) [英] Javascript Regex to specify what is allowed (rather than what is not)
问题描述
我一直在使用它:
str2 = str1.replace(/ [^ \w] / gi,'') ;
它工作正常,但由于不安全'^'$ c $而违反了JSLint c>如此处所述并此处。
It works fine, but falls foul of JSLint for having an insecure '^'
as outlined in the posts here and here.
大家一致认为最好使用 regex
来指定允许 的内容而不是。然而,没有人会演示如何做到这一点。我甚至在我面前有Flanagan和Crockford,但令我感到羞耻,我仍然不确定该怎么做。
The consensus is that it is better to use your regex
to specify what is allowed rather than what is not. No one ever demonstrates how to do this, however. I've even got Flanagan and Crockford in front of me here, but to my shame I'm still not sure what to do.
那么......你怎么样设置 str2
只允许在 str1 $ c $中找到
\w
个字符c>使用正面测试而非负面测试?
So... how do you set str2
to only allow the \w
characters found in str1
using a positive test rather than a negative one?
推荐答案
尝试 \ W
(大写W)。
\w
选择单词,而 \ W
选择不是字。并且在表达式中看起来更好一些。
The \w
selects word, while \W
selects not word. And looks a bit nicer in the expression.
这是一个 RegEx cheatsheet ,它在你编码时很方便!
Here's a RegEx cheatsheet, it comes handy while you're coding!
这篇关于Javascript Regex指定允许的内容(而不是不允许的内容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!