Home > Back-end >  Why is using ONLY indexOf returning different than using indexOf on a function?
Why is using ONLY indexOf returning different than using indexOf on a function?

Time:08-15

Good day, so I am trying to solve this one exercise. And try both methods of directly console.log a string.indexOf(subString) and using a function to count the occurences of a specific character/word on a string, which then returns both different values. Why is that? Here is the code:

const longText = `This is a very very long text. Do you understand how very long is this? Good for yah!`
const word = "very"

console.log(longText.indexOf(word));

function checkWord(longText, position) {
  var n = 0;

  var position = 0;

  while (true) {
    position = longText.indexOf(word, position)

    if (position != -1) {
      n  ;
      position  = word.length;
    } else {
      break;
    }
  }

  return n;
}

console.log(checkWord(longText, word));

// Expected output:   
//> 10 
//> 3

CodePudding user response:

longText.indexOf(word) does not return the number of occurrences.
It returns the index where it found the first occurrence (in this case at the 11th char). Since the characters of a string start from index 0 it means it starts on the index 10.

CodePudding user response:

So not entirely sure what you are trying to do but your code seems to be working out the position of where word is occuring (longText.indexOf(word)) and the number of occurences n. It seems you've done this on purpose as I can see you are caluclating the position where the string was last found, adding the length of the word to the current position then searching again from that position as the new starting position...position = longText.indexOf(word, position)

Although console.log(checkWord(longText, word)) 'word' here is a string, but

// writing in typescript
function checkWord(longText: string, position: string) {
  var n = 0;

  var position = 0;

you have a variable called position with the same name as an argument. You should refrain from doing this as it can cause confusion...as it did for me trying to understand.

    function checkWord(longText: string, indexWord: string) {
        var n = 0;

        var position = 0;

        while (true) {
            position = longText.indexOf(indexWord, position);

            if (position != -1) {
                n  ;
                position  = indexWord.length;
            } else {
                break;
            }
        }
        return n;
    }

this is what the function should be.

Addressing the results you see, 10 represents the character index of where the word is first found, and 3 represents the number of times the word was found in the string.

  • Related