的match
對象有一些所謂的index
,我認爲這是你在找什麼:
["axbxcxd", "x", "x", "x", index: 0, input: "axbxcxd"]
編輯
確定。我想我第一次沒有正確地回答這個問題。這裏是更新的答案:
re = /a(.*)b(.*)c(.*)d/;
str = "axbxcxd";
match = re.exec(str);
searchStr = match[1]; //can be either match[2],match[3]
searchStrLen = match[1].length; //can be either match[2],match[3]
var index, indices = []
var startIndex = 0;
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
console.log(indices[1]); // index of match[2]
console.log(indices[0]); // index of match[1]
console.log(indices[2]); // index of match[3] .. and so on, because some people don't get it with a single example
這可能是一個黑客,但應該工作。 工作小提琴:http://jsfiddle.net/8dkLq8m0/
只要用'match [2]'? – raser 2014-11-24 17:14:16
@raser給你第二個匹配組的*文本*,而不是位置 – Jamiec 2014-11-24 17:16:48
在匹配對象內搜索函數?匹配[2]。位置? – sln 2014-11-24 17:18:29