javascriptstring

How to find indices without using indexOf or other built in functions?


I have a situation where I need to find the index of the target string. My code works for single character, but not for characters more than 1. Any idea how can I approach this?

const findAllIndices =  (stringToCheck, target) => {
let index=[];
  for (let i = 0; i < stringToCheck.length;i++) {
    if (stringToCheck[i] === target) {
      index.push(i);
    }
  }
console.log(index)
}

findAllIndices('the dog jumps over the river', 'the')
findAllIndices('the dog jumps over the river', 'o')


Solution

  • If you can't use any built-in functions, you'll have to build up the substring at the i index from the number of characters in target, then check if the substring matches the target.

    const findAllIndices = (stringToCheck, target) => {
      const matchingIndicies = [];
      for (let i = 0; i < stringToCheck.length; i++) {
        let substring = '';
        for (let j = 0; j < target.length; j++) {
          substring += stringToCheck[i + j];
        }
        if (substring === target && substring.length === target.length) {
          matchingIndicies.push(i);
        }
      }
      console.log(matchingIndicies)
    }
    
    findAllIndices('the dog jumps over the river', 'the')
    findAllIndices('the dog jumps over the river', 'o')