JS string lastIndexOf()

🌙
手机阅读
本文目录结构

 lastIndexOf() 方法返回调用String 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex处从后向前搜索。如果没找到这个特定值则返回-1 。

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

语法

str.lastIndexOf(searchValue[, fromIndex])

参数

searchValue

一个字符串,表示被查找的值。如果searchValue是空字符串,则返回fromIndex

fromIndex可选

待匹配字符串searchValue的开头一位字符从 str的第fromIndex位开始向左回向查找。fromIndex默认值是 +Infinity。如果 fromIndex >= str.length ,则会搜索整个字符串。如果 fromIndex < 0 ,则等同于 fromIndex == 0

返回值

返回指定值最后一次出现的索引(该索引仍是以从左至右0开始记数的),如果没找到则返回-1。

描述

字符串中的字符被从左向右索引。首字符的索引(index)是 0,最后一个字符的索引是 stringName.length - 1

'canal'.lastIndexOf('a');     // returns 3 (没有指明fromIndex则从末尾l处开始反向检索到的第一个a出现在l的后面,即index为3的位置)
'canal'.lastIndexOf('a', 2);  // returns 1(指明fromIndex为2则从n处反向向回检索到其后面就是a,即index为1的位置)
'canal'.lastIndexOf('a', 0);  // returns -1(指明fromIndex为0则从c处向左回向检索a发现没有,故返回-1)
'canal'.lastIndexOf('x');     // returns -1
'canal'.lastIndexOf('c', -5); // returns 0(指明fromIndex为-5则视同0,从c处向左回向查找发现自己就是,故返回0)
'canal'.lastIndexOf('c', 0);  // returns 0(指明fromIndex为0则从c处向左回向查找c发现自己就是,故返回自己的索引0)
'canal'.lastIndexOf('');      // returns 5
'canal'.lastIndexOf('', 2);   // returns 2

Note: 'abab'.lastIndexOf('ab', 2) 将返回 2 而不是 0, 因为fromIndex只限制待匹配字符串的开头。

(例如’abadefgabm’.lastIndexOf(‘ab’, 7) 返回7,虽然查找的’ab’中的b已经在 index=8的位置了从index=7的a处向左查找仍是能找到自身a加上其后连成ab,因为fromIndex指的是待匹配字符串的开头那一个)

区分大小写

lastIndexOf 方法区分大小写。例如,下面的表达式返回 -1:

"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1

示例

例子:使用 indexOflastIndexOf

下例使用 indexOf 和 lastIndexOf 方法来定位字符串 “Brave new world” 中的值。

var anyString = "Brave new world";

console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
// Displays 8
console.log("The index of the first w from the end is " + anyString.lastIndexOf("w")); 
// Displays 10

console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));   
// Displays 6
console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
// Displays 6

规范

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262) String.prototype.lastIndexOf Standard
ECMAScript 2015 (6th Edition, ECMA-262)String.prototype.lastIndexOf Standard

相关链接

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了