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.
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
Coursera
Pros
  • Professional service
  • Flexible timetables
  • A variety of features to choose from
Main Features
  • Professional certificates of completion
  • University-level courses
  • Multiple Online degree programs
Datacamp
Pros
  • Great user experience
  • Offers quality content
  • Very transparent with their pricing
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

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');

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 03/03/2021
3176 People Used
Only 97 Left
Rating
5.0