回答
您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. 如何获取字符串中某个模式的所有匹配项的索引
- 3. 查找字符串中子字符串的所有索引
- 4. 如何获取字符串中模式的字符位置?
- 5. 如何查找不同字符串中的所有字符串索引?
- 6. 获取子字符串的索引
- 7. 如何查找字符串中的所有第一个索引?
- 8. Python:如何从没有索引的字符串中获取子串?
- 9. 获取红宝石中所有字符的索引
- 10. 如何获取数组中最高数字的所有索引?
- 11. 如何在swift中从字典中获取所有索引值?
- 12. 如何获得C中字符串的字符索引?
- 13. 如何获得字符串中的字符索引?
- 14. 在JavaScript中获取字符串的所有子字符串
- 15. 如何获取所有字符串格式参数
- 16. 获取字符从字符串列表索引到的字符
- 17. 如何通过索引从字符串中获取char?
- 18. 如何指出字符串中所有重复字符的索引位置
- 19. 如何获得斯卡拉字符串向量中的特定字符串的所有索引
- 20. 如何在JavaScript中获取日期格式模式字符串?
- 21. 如何从字符串中获取所有数字
- 22. 如何使用索引获取字符串中的字符但未使用charAt()?
- 23. 如何获取字符串数组中字符的索引位置
- 24. 如何获取jQuery中的字符串中的无效字符的所有值?
- 25. Python:如何获取字符串的索引
- 26. 如何获取字符串值的最后一个索引
- 27. 如何获取行datagridview中的所有数据字符串?
- 28. 如何获取字符串中存在的所有整数?
- 29. 获取查询命中索引 - 搜索字符串的前缀
- 30. 正则表达式获取字符串中的所有号码?
我喜欢的正则表达式exec方法。 – kennebec 2012-03-31 18:01:36