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

2020-04-06 16:14发布

I want something like this:

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

Is it possible?

标签: javascript
6条回答
▲ chillily
2楼-- · 2020-04-06 16:37

Another non-regex solution:

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'))

查看更多
smile是对你的礼貌
3楼-- · 2020-04-06 16:40

A non-regex variety:

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/

查看更多
Explosion°爆炸
4楼-- · 2020-04-06 16:42

If you only want to find simple characters, or character sequences, you can use indexOf [MDN]:

var haystack = "abcdab",
    needle = "a"
    index = -1,
    result = [];

while((index = haystack.indexOf(needle, index + 1)) > -1) {
    result.push(index);
}
查看更多
乱世女痞
5楼-- · 2020-04-06 16:44

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]

Helper function:

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"));
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-04-06 16:49

You can get all match indexes like this:

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

Working demo here: http://jsfiddle.net/jfriend00/r6JTJ/

查看更多
家丑人穷心不美
7楼-- · 2020-04-06 16:51

You could use / abuse the replace function:

var result = [];
"abcdab".replace(/(a)/g, function (a, b, index) {
    result.push(index);
}); 
result; // [0, 4]

The arguments to the function are as follows:

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 - #$*%
查看更多
登录 后发表回答