2012-03-31 92 views

回答

6

can useRegExp#exec方法几次:

var regex = /a/g; 
var str = "abcdab"; 

var result = []; 
var match; 
while (match = regex.exec(str)) 
    result.push(match.index); 

alert(result); // => [0, 4] 

Helper function

function getMatchIndices(regex, str) { 
    var result = []; 
    var match; 
    regex = new RegExp(regex); 
    while (match = regex.exec(str)) 
     result.push(match.index); 
    return result; 
} 

alert(getMatchIndices(/a/g, "abcdab")); 
+0

我喜欢的正则表达式exec方法。 – kennebec 2012-03-31 18:01:36

5

你可以使用/滥用replace function

var result = []; 
"abcdab".replace(/(a)/g, function (a, b, index) { 
    result.push(index); 
}); 
result; // [0, 4] 

该函数的自变量是为如下:

function replacer(match, p1, p2, p3, offset, string) { 
    // p1 is nondigits, p2 digits, and p3 non-alphanumerics 
    return [p1, p2, p3].join(' - '); 
} 
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); 
console.log(newString); // abc - 12345 - #$*% 
+0

聪明地使用'.replace()'函数。 – jfriend00 2012-03-31 18:17:40

0

你可以得到所有的匹配指标是这样的:

var str = "abcdab"; 
var re = /a/g; 
var matches; 
var indexes = []; 
while (matches = re.exec(str)) { 
    indexes.push(matches.index); 
} 
// indexes here contains all the matching index values 

工作演示在这里:http://jsfiddle.net/jfriend00/r6JTJ/

+0

为什么downvote? – jfriend00 2012-03-31 17:11:11

1

非正则表达式品种:

var str = "abcdabcdabcd", 
    char = 'a', 
    curr = 0, 
    positions = []; 

while (str.length > curr) { 
    if (str[curr] == char) { 
     positions.push(curr); 
    } 
    curr++; 
} 

console.log(positions); 

http://jsfiddle.net/userdude/HUm8d/

2

如果你只是想找个简单的字符,或字符序列,您可以使用indexOf[MDN]

var haystack = "abcdab", 
    needle = "a" 
    index = -1, 
    result = []; 

while((index = haystack.indexOf(needle, index + 1)) > -1) { 
    result.push(index); 
} 
+0

如果只查找单个字符的出现次数,这将是一个非常简单的方法,可能比正则表达式更好。 – jfriend00 2012-03-31 18:17:08

相关问题