| ★ wanayoo — archive 1999 http://developer.mozilla.org/ja/Core_JavaScript_1.5_Reference/Global_Objects/String/indexOf | Nouvelle recherche | Portail wanayoo |
呼び出す String オブジェクト 中で、指定された値が最初に現れたインデックスを返します。fromIndex から検索を始め、値が見つけられない場合、-1 を返します。
| String のメソッド | |
| 実装されたバージョン: | JavaScript 1.0, NES2.0 |
| ECMA バージョン: | ECMA-262 |
searchValue fromIndex
文字列における文字は左から右にインデックス化されます。一番最初の文字のインデックスは 0 で、stringName として呼び出された文字列における一番最後の文字は stringName.length - 1 です。
"Blue Whale".indexOf("Blue") // 0 を返します
"Blue Whale".indexOf("Blute") // -1 を返します
"Blue Whale".indexOf("Whale",0) // 5 を返します
"Blue Whale".indexOf("Whale",5) // 5 を返します
"Blue Whale".indexOf("",9) // 9 を返します
"Blue Whale".indexOf("",10) // 10 を返します
"Blue Whale".indexOf("",11) // 10 を返します
indexOf メソッドは大文字と小文字を区別します。例えば、以下の表現は -1 を返します。:
"Blue Whale".indexOf("blue")
indexOf と lastIndexOf の使用 以下の例は、 "Brave new world" という文字列において、与えられた値の位置を求めるために、indexOf と lastIndexOf を使用しています。
var anyString="Brave new world"
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w")) // 8 を表示します
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w")) // 10 を表示します
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")) // 6 を表示します
indexOf と 大文字と小文字の区別 以下の例は 2 つの文字列の変数を定義しています。それらの変数は、2 番目の文字列が大文字を含んでいることを除けば、同じ文字列を含んでいます。1 番目の writeln メソッドは 19 を表示します。 しかし、indexOf メソッドは大文字とと小文字を区別するので、"cheddar" という文字列は myCapString では見つけられません。ですから、writeln メソッドは -1 を表示します。
myString="brie, pepper jack, cheddar"
myCapString="Brie, Pepper Jack, Cheddar"
document.writeln('myString.indexOf("cheddar") is ' +
myString.indexOf("cheddar"))
document.writeln('<P>myCapString.indexOf("cheddar") is ' +
myCapString.indexOf("cheddar"))
Page last modified 14:43, 2008年1月7日 by Potappo