javascriptindexof

Writing indexOf function in JavaScript


I am new to JavaScript. I have created a indexof function in but it is not giving the correct output: Question is: /* Implement a function called indexOf that accepts two parameters: a string and a character, and returns the first index of character in the string. */

This is my code:

function indexOf(string, character) {
  let result = string;
  let i = 0;
  let output = 1;

  while (i < result.length) {
    if (result[i] === character) {
      output = output + indexOf[i];
    }
  }

  return output;
}

I want to know what i am doing wrong. Please Help.


Solution

  • Assuming from your question that the exercise is to only match the first occurrence of a character and not a substring (multiple characters in a row), then the most direct way to do it is the following:

    const indexOf = (word, character) => {
      for (let i = 0; i < word.length; i++) {
        if (word[i] === character) {
          return i;
        }
      }
    
      return -1;
    }
    

    If you also need to match substrings, leave a comment on this answer if you can't figure it out and I'll help you along.