lastIndexOf() メソッドは、呼び出す String オブジェクト中で、fromIndex から逆方向に検索し、指定された値が最後に現れるインデックスを返します。値が見つけられない場合、-1 を返します。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
構文
str.lastIndexOf(searchValue[, fromIndex])
引数
searchValue- 検索する値を表す文字列です。
searchValueが空文字列だった場合、fromIndexが返されます。 fromIndexOptional- 文字列内で検索を始める位置です。デフォルト値は
+Infinityです。fromIndex >= str.lengthの場合、文字列全体が検索対象になります。fromIndex < 0の場合、0の場合と同じ動作をします。
戻り値
指定された値が最後に現れるインデックスを返します。見つからなかった場合は -1 です。
説明
文字列内の文字は左から右にインデックス化されます。一番最初の文字のインデックスは 0 で、一番最後の文字のインデックスは str.length - 1 です。
'canal'.lastIndexOf('a'); // 3 を返す
'canal'.lastIndexOf('a', 2); // 1 を返す
'canal'.lastIndexOf('a', 0); // -1 を返す
'canal'.lastIndexOf('x'); // -1 を返す
'canal'.lastIndexOf('c', -5); // 0 を返す
'canal'.lastIndexOf('c', 0); // 0 を返す
'canal'.lastIndexOf(''); // 5 を返す
'canal'.lastIndexOf('', 2); // 2 を返す
注: 'abab'.lastIndexOf('ab', 2) は 0 ではなく 2 を返します。fromIndex は検索の開始位置を示しているにすぎないからです。
大文字と小文字の区別
lastIndexOf() メソッドは 大文字と小文字を区別します。例えば、以下の表現は -1 を返します。
'Blue Whale, Killer Whale'.lastIndexOf('blue'); // returns -1
例
indexOf() と lastIndexOf() の使用
以下の例は、 "Brave new world" という文字列において、与えられた値の位置を求めるために、indexOf() と lastIndexOf() を使用しています。
var anyString = 'Brave new world';
console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
// 8 を表示する
console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w'));
// 10 を表示する
console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
// 6 を表示する
console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
// 6 を表示する
仕様
ブラウザー実装状況
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| デスクトップ | モバイル | サーバー | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lastIndexOf | Chrome 完全対応 1 | Edge 完全対応 12 | Firefox 完全対応 1 | IE 完全対応 6 | Opera 完全対応 3 | Safari 完全対応 1 | WebView Android 完全対応 1 | Chrome Android 完全対応 18 | Firefox Android 完全対応 4 | Opera Android 完全対応 10.1 | Safari iOS 完全対応 1 | Samsung Internet Android 完全対応 1.0 | nodejs 完全対応 0.1.100 |
凡例
- 完全対応
- 完全対応