如何在javascript中找到所有字符串出现的索引?

问题描述:

使用indexOf函数我们可以找到特定字符串的索引。如何获取string的所有出现的索引。有没有最简单的方法呢?

Using indexOf function we can find the index of particular string. How to get the index of all the occurrences of string.Is there any simplest way to do it?

Tty

Tty
string myString= "Check occurrences within this string.";
int count = myString.match(/in/g);// Search for 'in' occurrences in string


使用正则表达式:

Use a regex:
var regex = /,/g;
var instr = "1,2,3,4";
var current;
var matchIndexes = [];

while ((current = regex.exec(instr)) != null)
{
   matchIndexes.push(current.index);
}