使用Javascript捕获多次出现的相同字符串的各个索引

时间:2018-09-16 15:59:24

标签: javascript

输入

Lets go to play football.
I love football.

在这里,我如何获得第一个“足球”和第二个“足球”的起始索引和终止索引?

var start_index = input.indexOf('football');

这只是给我足球第一次出现的索引。

3 个答案:

答案 0 :(得分:0)

文档indexOf()

是了解此类情况的好地方

如您所见,此函数接受第二个参数,该参数用于确定从何处开始搜索。

这意味着您可以像这样获得第二次出现的索引:

var str = "Lets go to play football.\nI love football.";
var firstIndex = str.indexOf("football");
var secondIndex = str.indexOf("football", firstIndex + 1);

console.log(firstIndex, secondIndex);

要在所有情况下都这样做,可以使用循环:

var str = "Lets go to play football.\nI love football.\nI love football.";
var indexes = [];
var latestIndex = -1;

while(true){
    latestIndex = str.indexOf("football", latestIndex + 1);
    if(latestIndex === -1){
       break;
    }
    indexes.push(latestIndex);
}

console.log(indexes);

答案 1 :(得分:0)

一种选择是使用RegExp.prototype.exec函数:

var str = "Lets go to play football.\nI love football.";
var reg = /football/g, indices = [];
while (reg.exec(str) !== null) {
  indices.push(reg.lastIndex - reg.source.length);
}
// indices:
//   Array(2)
//     0: 16
//     1: 33

在上面的代码中,str是输入,indices是索引(索引)的数组。

答案 2 :(得分:0)

您可以使用此功能来查找所有事件。

const s = 'Lets go to play football.\n' +
    'I love football.';

const findIndices = (s, word) => {
    let index = -1;
    while(1) {
      index = s.indexOf(word, index + 1);
      if (index === -1) return;
      console.log(index);
  }
};

findIndices(s, 'football');