回答
您can use的RegExp#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]
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"));
你可以使用/濫用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 - #$*%
聰明地使用'.replace()'函數。 – jfriend00 2012-03-31 18:17:40
你可以得到所有的匹配指標是這樣的:
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
爲什麼downvote? – jfriend00 2012-03-31 17:11:11
非正則表達式品種:
var str = "abcdabcdabcd",
char = 'a',
curr = 0,
positions = [];
while (str.length > curr) {
if (str[curr] == char) {
positions.push(curr);
}
curr++;
}
console.log(positions);
如果你只是想找個簡單的字符,或字符序列,您可以使用indexOf
[MDN]:
var haystack = "abcdab",
needle = "a"
index = -1,
result = [];
while((index = haystack.indexOf(needle, index + 1)) > -1) {
result.push(index);
}
如果只查找單個字符的出現次數,這將是一個非常簡單的方法,可能比正則表達式更好。 – jfriend00 2012-03-31 18:17:08
- 1. 獲取所有字符串中的任意字的索引
- 2. 在C#中查找字符串中的所有模式索引#
- 3. 如何獲得搜索字符串的所有索引
- 4. 獲取字符串索引
- 5. 如何獲取字符串中某個模式的所有匹配項的索引
- 6. 獲取索引字符串中的所有字符元素匹配R
- 7. Lua模式:如何獲取所需的字符串
- 8. 查找字符串中子字符串的所有索引
- 9. 如何獲取字符串中模式的字符位置?
- 10. 如何在字符串中反向搜索以獲取索引?
- 11. 如何查找不同字符串中的所有字符串索引?
- 12. 使用正則表達式獲取字符串中模式的索引
- 13. 如何查找字符串中的所有第一個索引?
- 14. 獲取子字符串的索引
- 15. 獲取strings.xml中的所有字符串
- 16. 返回ruby中字符串中所有字符的索引
- 17. Python:如何從沒有索引的字符串中獲取子串?
- 18. 獲取紅寶石中所有字符的索引
- 19. 如何獲取數組中最高數字的所有索引?
- 20. 查找字符串中所有字符的索引
- 21. 如何在swift中從字典中獲取所有索引值?
- 22. 如何獲得C中字符串的字符索引?
- 23. 如何獲得字符串中的字符索引?
- 24. 如何獲取所有字符串格式參數
- 25. 獲取字符串中包含的所有字符串
- 26. 在JavaScript中獲取字符串的所有子字符串
- 27. 獲取字符串中所有子字符串的出現
- 28. 獲取第n個索引字符串
- 29. 獲取索引位置從字符串
- 30. 通過索引獲取字符串 - Java
我喜歡的正則表達式exec方法。 – kennebec 2012-03-31 18:01:36