且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取字符串中模式的所有索引?

更新时间:2023-02-21 15:51:44

可以使用 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"));