返回指定的字符串首次出现的位置

indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。

语法

stringObject.indexOf(substring, startpos)

参数说明:

返回指定的字符串首次出现的位置_第1张图片

说明:

1.该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 substring。

2.可选参数,从stringObject的startpos位置开始查找substring,如果没有此参数将从stringObject的开始位置查找。

3.如果找到一个 substring,则返回 substring 的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。

注意:1.indexOf() 方法区分大小写。

2.如果要检索的字符串值没有出现,则该方法返回 -1。

例如: 对 "I love JavaScript!" 字符串内进行不同的检索:

以上代码的输出:

0
4
9

 示例:

DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>string对象 title>
<script type="text/javascript">
  var mystr="Hello World!"
  document.write(mystr.indexOf("H")+"
"); document.write(mystr.indexOf("l")+"
"); document.write(mystr.indexOf("W"),8); script> head> <body> body> html>

以上代码的输出:

0

2

68

 

转载于:https://www.cnblogs.com/multistars/p/5833922.html

你可能感兴趣的:(返回指定的字符串首次出现的位置)