JavaScript参考手册
字符串 | String
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) |
字符串 | String相关
JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络