Code has been added to clipboard!


Reading time 2 min
Published Sep 8, 2017
Updated Oct 10, 2019

indexOf JavaScript: Main Tips

  • The indexOf JavaScript returns the position of the first occurrence of a specified value inside a string variable.
  • If the specified value is not found, the return value is -1.
  • The .indexOf JavaScript method is case sensitive.

indexOf() Function Explained

The indexOf JavaScript gets information about the string content. After a specified value is found in a string, the function returns the position of the first occurrence.

The following example illustrates how the JavaScript string indexOf function will search a string to find a specified value:

var sampleStr = "Hi, Mark!";

Characters you search for are indexed from left to right. For instance, the value found in the first index would trigger the return value of 0.

Note: JavaScript is case sensitive. If a string contains a word Swim, the .indexof JavaScript function won't find swim.

Correct Syntax of indexOf

At the beginning of the JS indexOf function, you need to specify the string to be searched.

string.indexOf(searchValue, start)

The method also accepts two parameters:

  • The required parameter of searchValue indicates the content you want to search for in a string.
  • The optional start parameter indicates the position of the string in which the search will begin. If not specified, the search will start at the beginning.
const sampleStr = 'Hi, Mark!';
sampleStr.indexOf('M', 10);

Return Values

The indexOf JavaScript returns the location of the specified value in a string. The value position is indicated with a number. If the function does not detect any matches, it will display -1.

const sampleStr = 'Hi, Mark!';

Web Development Course:

Web Development Course

Certificate Included
900h of content
For beginners