Javascript 允许在正则表达式中使用“/”正斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31566808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allow "/" forward slash in regular expression
提问by webdev5
var patt = /^(?=.*[a-zA-Z0-9.!@#&*\-\u0080-\u052F])[a-zA-Z0-9\s.!@#&*',\-\u0080-\u052F]*$/;
console.log(patt.test("\u002f"));
I know that u002f is a forward slash in Unicode. I've tried adding that to the pattern as well as "/" and haven't been able to get it to log true yet.
我知道 u002f 是 Unicode 中的正斜杠。我已经尝试将它添加到模式以及“/”中,但还没有能够让它记录为真。
回答by slartidan
You can escape a /
character, by using \/
.
您可以/
使用来转义字符\/
。
Using unicode will actually result in the absolute sameresult, as using the character itself - and therefore will not solve your problem.
使用 unicode 实际上会产生与使用字符本身完全相同的结果 - 因此不会解决您的问题。
回答by Wiktor Stribi?ew
It is easy to add a forward slash, just escape it. No need using any character references or entities.
添加正斜杠很容易,只需将其转义即可。无需使用任何字符引用或实体。
var patt = /^(?=.*[a-zA-Z0-9.!@#&*\-\u0080-\u052F])[\/a-zA-Z0-9\s.!@#&*',\-\u0080-\u052F]*$/;
^
var patt = /^(?=.*[a-zA-Z0-9.!@#&*\-\u0080-\u052F])[\/a-zA-Z0-9\s.!@#&*',\-\u0080-\u052F]*$/;
alert(patt.test("/test"));