2012-03-31 28 views

Trả lời

6

Bạn can use các RegExp#exec phương pháp nhiều lần:

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

Tôi thích phương thức exec RegExp. – kennebec

5

Bạn có thể sử dụng/lạm dụng replace function:

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

Các tham số cho hàm như sau:

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

+1 để sử dụng thông minh hàm '.replace()'. – jfriend00

0

Bạn có thể nhận được tất cả các chỉ số trận đấu như thế này:

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 

Làm việc giới thiệu ở đây: http://jsfiddle.net/jfriend00/r6JTJ/

+0

Tại sao lại là downvote? – jfriend00

1

Một loạt phi regex:

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

Nếu bạn chỉ muốn tìm các ký tự đơn giản hoặc chuỗi ký tự, bạn có thể sử dụng indexOf[MDN]:

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

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

Nếu một người chỉ tìm kiếm sự xuất hiện của một nhân vật duy nhất, đây sẽ là một cách rất đơn giản để làm điều đó và có thể thực hiện tốt hơn so với regex. – jfriend00

Các vấn đề liên quan