繁体   English   中英

正则表达式返回真假

[英]Regex Returning True and False

 windowLocation = /(^\/t\d+)|(^\/post\?.+(post|reply){1})|(\/privmsg\?.+(post|reply){1})/g;
 windowLocation.test(window.location.pathname+window.location.search);

此代码保持return true然后再次尝试将返回false 我需要测试像这样的路径名和搜索

 /t12
 /post?t=2&mode=reply
 /privmsg?mode=reply&p=62

关于为什么这总是返回true和false的任何建议?

这是由于在正则表达式中使用了/g (全局)标志。 如果删除它会没事的。

windowLocation = /(^\/t\d+)|(^\/post\?.+(post|reply){1})|(\/privmsg\?.+(post|reply){1})/;

在正则表达式中使用全局标志时,将在不同的调用RegExp#test(string)之间维护lastIndex属性。 lastIndex属性是开始下一个匹配的索引。

通过上述正则表达式,我得到:

windowLocation.test("/t12");
true
windowLocation.test("/t12");
true
windowLocation.test("/t12");
true

参考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM