在线文档教程

string.lastIndexOf

string.lastIndexOf

lastIndexOf() 方法返回指定值在调用该方法的字符串中最后出现的位置,如果没找到则返回 -1。从该字符串的后面向前查找,从fromIndex处开始。

语法

str.lastIndexOf(searchValue[, fromIndex])

参数

searchValue一个字符串,表示被查找的值。

返回值

最后一次出现索引的位置; 如果没有找到返回-1

描述

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

'canal'.lastIndexOf('a' // returns 3 'canal'.lastIndexOf('a', 2 // returns 1 'canal'.lastIndexOf('a', 0 // returns -1 'canal'.lastIndexOf('x' // returns -1 'canal'.lastIndexOf('c', -5 // returns 0 'canal'.lastIndexOf('c', 0 // returns 0 'canal'.lastIndexOf('' // returns 5 'canal'.lastIndexOf('', 2 // returns 2

区分大小写

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') // logs 8 console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w') // logs 10 console.log('The index of "new" from the beginning is ' + anyString.indexOf('new') // logs 6 console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new') // logs 6

规范

SpecificationStatusComment
ECMAScript 1st Edition (ECMA-262)StandardInitial definition.
ECMAScript 5.1 (ECMA-262)The definition of 'String.prototype.lastIndexOf' in that specification.Standard
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'String.prototype.lastIndexOf' in that specification.Standard
ECMAScript Latest Draft (ECMA-262)The definition of 'String.prototype.lastIndexOf' in that specification.Living Standard

浏览器兼容性

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic Support(Yes)(Yes)(Yes)6(Yes)(Yes)

FeatureAndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic Support(Yes)(Yes)(Yes)(Yes)8.1(Yes)(Yes)