我一直在嘗試使用簡單的jQuery操作來動態匹配和存儲頁面上的所有錨標籤及其文本。但我發現了一個奇怪的行爲。當你使用match()或exec()時,如果你指定針作爲一個單獨的RegExp對象或模式變量,那麼你的查詢只能在乾草堆中匹配數十個實例。Javascript匹配和RegExp問題 - 奇怪行爲
如果你指定這樣
match(/needle/gi)
模式則針的每個實例相匹配。
這是我的代碼。
你甚至可以啓動Firebug並在此頁面上嘗試此代碼。
var a = {'text':'','parent':[]};
$("a").each(function(i,n) {
var module = $.trim($(n).text());
a.text += module.toLowerCase() + ',' + i + ',';
a.parent.push($(n).parent().parent());
});
var stringLowerCase = 'b';
var regex = new RegExp(stringLowerCase, "gi");
//console.log(a.text);
console.log("regex 1: ", regex.exec(a.text));
var regex2 = "/" + stringLowerCase + "/";
console.log("regex 2: ", a.text.match(regex2));
console.log("regex 3: ", a.text.match(/b/gi));
對我來說,它返回:
regex 1: ["b"]
regex 2: null
regex 3: ["b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"]
任何人都可以解釋這種行爲的根源在哪裏?
編輯:我忘了提及,對於regex1,不管是否爲全局和不區分大小寫的匹配添加標誌「gi」都沒有什麼區別。它仍然只返回一場比賽。
EDIT2:解決了我自己的問題。我仍然不知道爲什麼一個regex1只匹配一個實例,但我設法匹配使用match()和regex1的所有實例。
因此,這個匹配所有動態!
var regex = new RegExp(stringLowerCase, "gi");
console.log("regex 2: ", a.text.match(regex));
什麼是a.text – 2009-07-16 11:35:18
一個的內容只是兩個元素的對象。我在代碼的頂部定義了它。它的上下文可能是文檔對象。 – picardo 2009-07-16 11:37:22