Latest Code Tutorials

Javascript String indexOf Example | String.prototype.indexOf()


Javascript String indexOf Example | String.prototype.indexOf() is today’s leading topic. The indexOf() method returns an index within the calling String object of the first occurrence of a specified value, starting the search at fromIndex(). Returns -1 if the value is not found. The javascript string indexOf() method is case sensitive.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript String indexOf Example

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called stringName is stringName.length-1. The syntax of Javascript string indexOf() method is following.

string.indexOf(searchvalue, start)

The searchValue is a required field. It is the string that we need to search for.

The start parameter is optional. The default is 0 at which position to start the search in a string.

The indexOf returns the index of the string (0-based) where the searchValue is found for the first time. If the searchValue cannot be found in the string then the function returns -1. The method checks each substring against searchValue using strict equality (===), which means this method is case sensitive.

// app.js

let str = 'Winter is coming';
let position = str.indexOf('coming');



Javascript String indexOf Example | String.prototype.indexOf()

The indexOf method is case sensitive. For example, the following expression returns -1.

// app.js

let str = 'Winter is coming';
let position = str.indexOf('winter');


Here, we are looking for small-cap winter which is not present in the string. So it will return -1 position.

String indexOf to count occurrences of a letter in a string

We will count the occurrences of a character in a string using the following code.

// app.js

const str = 'Winter is coming';
let count = 0;
let position = str.indexOf('i');

while (position !== -1) {
  position = str.indexOf('i', position + 1);


So, in the above code, we have provided one string, and we will count the i character appear in that screen and printing on the console.


Javascript String indexOf Example

At last, Javascript String indexOf Example | String.prototype.indexOf() is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.