string.lastIndexOf
lastIndexOf()
方法返回指定值在调用该方法的字符串中最后出现的位置,如果没找到则返回 -1。从该字符串的后面向前查找,从fromIndex
处开始。
语法
str.lastIndexOf(searchValue[, fromIndex])
参数
searchValue
一个字符串,表示被查找的值。
fromIndex
从调用该方法字符串的此位置处开始查找。可以是任意整数。默认值为 str.length
。如果为负值,则被看作 0。如果 fromIndex > str.length
,则 fromIndex
被看作str.length
。
返回值
最后一次出现索引的位置; 如果没有找到返回-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
示例
例子:使用 indexOf
和lastIndexOf
下例使用 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
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial 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 | |
浏览器兼容性
Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic Support | (Yes) | (Yes) | (Yes) | 6 | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
---|---|---|---|---|---|---|---|
Basic Support | (Yes) | (Yes) | (Yes) | (Yes) | 8.1 | (Yes) | (Yes) |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com