码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript indexOf() 方法和 lastIndexOf() 方法

时间:2017-08-26 12:53:57      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:blog   ast   ima   val   http   提示   它的   相同   tin   

一,定义和用法

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

lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索。

语法

stringObject.indexOf(searchvalue,fromindex)
stringObject.lastIndexOf(searchvalue,fromindex)

indexOf() 方法

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

 lastIndexOf() 方法

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

 

返回值

lastIndexOf() 方法如果在 stringObject 中的 fromindex 位置之前存在 searchvalue,则返回的是出现的最后一个 searchvalue 的位置。

说明

 indexOf() 方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex 处或字符串的开头(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue 的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。

 lastIndexOf() 方法将从尾到头地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex 处或字符串的结尾(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue 的第一个字符在 stringObject 中的位置。stringObject 中的字符位置是从 0 开始的。

二,提示和注释

注释:indexOf() 方法和 lastIndexOf() 方法都对大小写敏感!

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

实例1:

技术分享
<html>
<body>

<script type="text/javascript">

var str="Hello world!"
document.write(str.indexOf("Hello") + "<br />")
document.write(str.indexOf("World") + "<br />")
document.write(str.indexOf("world"))

</script>

</body>
</html>
技术分享

效果如下:

技术分享

 实例2:

技术分享
<html>
<body>

<script type="text/javascript">

var str="Hello world!"
document.write(str.lastIndexOf("Hello") + "<br />")
document.write(str.lastIndexOf("World") + "<br />")
document.write(str.lastIndexOf("world"))

</script>

</body>
</html>
技术分享

效果如下:

技术分享 

(不知读者是否会有疑问,为何二者的结果相同?在此啰嗦下,因为 lastIndexOf()方法虽然是从后往前搜索,但返回的位置是从前开始数数和计算的,所以结果如上。)

 

轉載:http://www.cnblogs.com/iceflorence/p/5825286.html

2017-08-26 11:08:00

JavaScript indexOf() 方法和 lastIndexOf() 方法

标签:blog   ast   ima   val   http   提示   它的   相同   tin   

原文地址:http://www.cnblogs.com/guangzhou11/p/7434809.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!