JavaScript indexOf()Method

String 对象参考手册JavaScript String Object

Example

Find the string "welcome":

var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");

nOutput result:


Try it yourself »

Definition and Usage

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

If no matching string is found, -1 is returned.

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

Tip:You can also check out similar methodslastIndexOf() 。


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the indexOf() method.


Syntax

string.indexOf(searchvalue,start)

Parameter Values

Parameter Description
searchvalue Required. Specifies the string value to be retrieved.
start Optional integer parameter. Specifies the position in the string to start the search. Its legal values are 0 to string Object.length - 1. If this parameter is omitted, the search will start from the first character of the string.

Return Value

Type Description
Number The position of the first occurrence of the specified string, or -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");

nOutput result:


Try it yourself »

Example

Start searching for the first occurrence of the character "e" from the fifth position in the string:

var str="Hello world, welcome to the universe.";
var n=str.indexOf("e",5);

nOutput result:


Try it yourself »


String 对象参考手册JavaScript String Object

Other Extensions