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

How to get all indexes of a pattern in a string?

本文关键字:索引 模式 获取 字符串      更新时间:2023-09-26

我想要这样的东西:

"abcdab".search(/a/g) //return [0,4]

有可能吗?

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

您可以使用/滥用替换函数:

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 - #$*%

如果只想查找简单字符或字符序列,可以使用indexOf[MDN]:

var haystack = "abcdab",
    needle = "a"
    index = -1,
    result = [];
while((index = haystack.indexOf(needle, index + 1)) > -1) {
    result.push(index);
}

您可以获得所有匹配索引,如下所示:

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

在此处进行演示:http://jsfiddle.net/jfriend00/r6JTJ/

非正则表达式变体:

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/

另一个非正则表达式解决方案:

function indexesOf(str, word) {
   const split = str.split(word)
   let pointer = 0
   let indexes = []
   for(let part of split) {
      pointer += part.length
      indexes.push(pointer)
      pointer += word.length
   }
   indexes.pop()
   return indexes
}
console.log(indexesOf('Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate', 'JavaScript'))

基于@jfriend00答案,但已整理:

const getAllIndices = (str, strToFind) => {
  const regex = RegExp(strToFind, 'g')
  const indices = []
  let matches
  while (matches = regex.exec(str)) indices.push(matches.index)
  return indices
}
console.log(getAllIndices('hello there help me', 'hel'))
console.log(getAllIndices('hello there help me', 'help'))
console.log(getAllIndices('hello there help me', 'xxxx'))