簡體   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