🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

string.indexOf

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.
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
edX
Pros
  • A wide range of learning programs
  • University-level courses
  • Easy to navigate
  • Verified certificates
  • Free learning track available
Main Features
  • University-level courses
  • Suitable for enterprises
  • Verified certificates of completion

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:

Example
var sampleStr = "Hi, Mark!";
sampleStr.indexOf("Hi", 0);

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.
Example
const sampleStr = 'Hi, Mark!';
sampleStr.indexOf('M');
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.

Example
const sampleStr = 'Hi, Mark!';
sampleStr.indexOf('John');
sampleStr.indexOf('mark');