简体   繁体   中英

Capture respective index of same string with multiple occurences using Javascript

input

Lets go to play football.
I love football.

Here, how do I get the respective start and end index of both the first 'football' and the second 'football'?

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

This only gives me the index of the first occurence of football .

A good place to find out about these kind of things is the documentation indexOf()

As you can see, this function accepts a second parameter that is used to determine form where to start the search.

That means that you can get the index of the second occurrence like this:

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

And to do that for all the occurrences, you can use a loop:

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

One option is using RegExp.prototype.exec function:

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

In the above code str is the input and indices is an array of indices (indexes).

You can use this function that will find every occurence.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM