JavaScript indexOf

JavaScript indexof 方法返回指定字符串的第一次出现的位置索引。如果找不到指定的字符串,indexof 函数将返回 -1。indexof 函数的语法是

String_Object.indexof(Substring, Starting_Position)
  • 子字符串:要搜索的字符串_对象中的字符串。
  • 起始位置或从索引开始(可选):如果要指定起始点(起始索引位置),请在此处选择索引值。

如果起始位置是负数,indexof 从 0 开始查找。如果起始位置超出范围,则从最高索引号开始查找。

JavaScript indexof 示例

此示例将帮助您理解此方法。第三行代码开始搜索,找到子字符串“Script”的索引位置,并将值存储在 Str3 中。

在下一行中,我们在 Str1 中查找不存在的“abc”。由于 JavaScript 字符串 IndexOf 找不到子字符串,它返回 -1 作为输出。

对于 Str5,我们在 Str2 中查找“abc”。

从上面可以看出,尽管 abc 重复出现多次,indexof 字符串函数仍写入了第一次出现的索引位置。现在,让我们将起始位置从默认的 0 修改为 10。这意味着以下代码将返回从 10 开始的字符串 abc 的第一次出现。

<!DOCTYPE html>
<html>
<head>
    <title> Example</title>
</head>
<body>
    <h1> Example </h1>
<script>
 var Str1 = "Learn JavaScript at Tutorial Gateway.org";
 var Str2 = "We are abc working at abc company";
 var Str3 = Str1.indexOf("Script");
 var Str4 = Str1.indexOf("abc"); // Non existing item
 var Str5 = Str2.indexOf("abc");
 var Str6 = Str1.indexOf("Script", 5);
 var Str7 = Str2.indexOf("abc", 10);
 
 document.write("<b> Index position of Script is:</b> " + Str3);
 document.write("<br \> <b> Index position of abc is:</b> " + Str4);
 document.write("<br \> <b> Index position of abc is:</b> " + Str5);
 document.write("<br \> <b> Index position of Script is:</b> " + Str6);
 document.write("<br \> <b> Index position of abc is:</b> " + Str7);
</script>
</body>
</html>

提示:JavaScript 函数中的索引位置从 0 开始,而不是 1。

IndexOf Function Example