Javascript - String indexOf() Method

The indexOf() method returns the position of the first occurrence of a specified value in a string.

Description

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

The indexOf() method is case sensitive.

Syntax

string.indexOf(searchvalue,start)

Parameter Values

Parameter Require Description
searchvalue Required. The string to search for
start Optional.Default 0. At which position to start the search

Return

A Number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs

Example

Search a string for "welcome":

Demo

//locate where in the string a specifed value occurs.
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
console.log(n);//  www. j  ava 2  s.c om

//Find the first occurrence of the letter "e" in a string:
//locate the first occurance of the letter "e".
str = "Hello world, welcome to the universe.";
n = str.indexOf("e");
console.log(n);

Result