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