简体   繁体   中英

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);

This code keeps return true then if you try it again it returns false . I need to test pathnames and searches that are like so

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

Any suggestions as to why this keeps returning both true and false?

It is due to use of /g (global) flag in your regex. If you remove it will be fine.

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

When you use the global flag in the regex, the lastIndex property is maintained between different calls RegExp#test(string) . The lastIndex property is the index at which to start the next match.

With above regex I get:

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

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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