0

How to find all Indexes of as specified word within a lengthy string?

let word = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate';

Find the Indexes of word "JavaScript" from the above string in JavaScript code? Actually, its my interview question.

5

2 Answers 2

1

You can use the following code.

let str = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate';
function findAllIndexes(string,word){
  let result = [];
  let dif = 0;
  while(true){
    let index = string.indexOf(word);
    if(index === -1) break;
    else{
      result.push(index + dif);
      let cur = string.length;
      string = string.substring(index + word.length);
      dif += cur - string.length;
    }
  }
  return result;
}
console.log(findAllIndexes(str,"JavaScript"));

0

You can do this using a regular expression.

let word = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate';
var regex = /JavaScript/gi,result,indices=[];
while((result=regex.exec(word)))
{
  indices.push(result.index);
}
console.log(indices);
4
  • 2
    Not to police too hard here but this question is blatantly off topic, and should not be answered. Doing so encourages this user (and others) to come back and simply ask "Hey someone write my code for me", knowing that they'll get an answer. Feb 21, 2019 at 17:14
  • Yes, Thanks @obscure. It worked. Feb 21, 2019 at 17:14
  • @Tyler Roper - I see what you mean. It's just the 'little' helper deep inside me that just can't resist. I'll remember your words.
    – obscure
    Feb 21, 2019 at 17:54
  • @obscure I hear you and often have to fight the same instinct. Your heart's in the right place! Feb 21, 2019 at 18:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.