Latest web development tutorials

JavaScript indexOf () method

String Object Reference JavaScript String Object

Examples

Search string "welcome":

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

n output:


try it"

Definition and Usage

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

If no matching string found -1 is returned.

Note: indexOf () method is case-sensitive.

Tip: You can also view a similar manner lastIndexOf () .


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support indexOf () method.


grammar

string.indexOf( searchvalue , start )

Parameter Value

参数 描述
searchvalue 必需。规定需检索的字符串值。
start 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 string Object.length - 1。如省略该参数,则将从字符串的首字符开始检索。

return value

类型 描述
Number 查找指定字符串第一次出现的位置,如果没找到匹配的字符串则返回 -1。

technical details

JavaScript version: 1.0


More examples

Examples

Find the string of characters "e" for the first time to appear:

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

n output:


try it"

Examples

The fifth position in the string Find position of the character "e" first appears:

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

n output:


try it"


String Object Reference JavaScript String Object