如何获取字符串中模式的所有索引? [英] How to get all indexes of a pattern in a string?
本文介绍了如何获取字符串中模式的所有索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要这样的东西:
"abcdab".search(/a/g) //return [0,4]
有可能吗?
推荐答案
您可以使用 RegExp #exec
方法多次:
You can use the RegExp#exec
method several times:
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"));
这篇关于如何获取字符串中模式的所有索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文