Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript indexOf() Method

JavaScript indexOf() Method

String Object Reference JavaScript String object

Example

Find the string "welcome":

var str="Hello world, welcome to the universe.";

var n=str.indexOf("welcome");

n Output result:

Try it »


Definition and Usage

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

If no matching string is found, it returns -1.

Note: The indexOf() method is case-sensitive.

Tip: You can also check similar methods lastIndexOf() .


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the indexOf() method.


Syntax

string

.indexOf(

searchvalue

,

start

)

Parameter value

Parameters Description
searchvalue Required. Specifies the string value to search for.
start Optional integer parameter. Specifies the position in the string where the search begins. Its valid range is 0 to stringObject.length - 1. If this parameter is omitted, the search starts from the first character of the string.

Return Value

Type Description
Number Find the first occurrence of a specified string, returning -1 if no matching string is found.

Technical Details

JavaScript version: 1.0

More examples

Example

Find the first occurrence of the character "e" in the string:

var str="Hello world, welcome to the universe.";

var n=str.indexOf("e");

n Output result:

Try it »

Example

Find the first occurrence of the character "e", starting from the fifth position in the string:

var str="Hello world, welcome to the universe.";

var n=str.indexOf("e",5);

n Output result:

Try it »


String Object Reference JavaScript String object