Core JavaScript 1.5 Reference:Global Objects:String:lastIndexOf
出典: MDC
目次 |
[編集] 概要
呼び出す String オブジェクト 中で、指定された値が最後に現れるインデックスを返します。値が見つけられない場合、-1 を返します。呼び出す文字列は、fromIndex から検索を始め、逆方向に検索されます。
| String のメソッド | |
| 実装されたバージョン: | JavaScript 1.0, NES2.0 |
| ECMA バージョン: | ECMA-262 |
[編集] 構文
lastIndexOf(searchValue[, fromIndex])
[編集] パラメータ
-
searchValue - 検索する値を表す文字列。
-
fromIndex - 呼び出す文字列内の検索を始めるための位置。0 とその文字列の長さの間にある整数を指定できます。デファルトの値は 0 です。
[編集] 詳細
文字列における文字は左から右にインデックス化されます。一番最初の文字のインデックスは 0 で、一番最後の文字のインデックスは stringName.length - 1 です。
"canal".lastIndexOf("a") // 3 を返します
"canal".lastIndexOf("a",2) // 1 を返します
"canal".lastIndexOf("a",0) // -1 を返します
"canal".lastIndexOf("x") // -1 を返します
lastIndexOf メソッドは 大文字と小文字を区別します。例えば、以下の表現は -1 を返します。:
"Blue Whale, Killer Whale".lastIndexOf("blue")
[編集] 例
[編集] 例: indexOf と lastIndexOf の使用
以下の例は、 "Brave new world" という文字列において、与えられた値の位置を求めるために、indexOf と lastIndexOf を使用しています。
var anyString="Brave new world"
// 8 を表示します
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w"))
// 10 を表示します
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w"))
// 6 を表示します
document.write("<P>The index of 'new' from the beginning is " +
anyString.indexOf("new"))
// 6 を表示します
document.write("<P>The index of 'new' from the end is " +
anyString.lastIndexOf("new"))