JavaScript文字列indexOf()
例
「welcome」の文字列を検索します。
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome");
「ようこそ」の文字列を検索します。
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("Welcome");
「e」の最初の出現を見つけます:
let text = "Hello world, welcome to the universe.";
text.indexOf("e");
位置5から始まる「e」の最初の出現を見つけます。
let text = "Hello world, welcome to the universe.";
text.indexOf("e", 5);
「a」の最初の出現を見つけます:
let text = "Hello world, welcome to the universe.";
text.indexOf("a");
定義と使用法
このindexOf()
メソッドは、文字列内で最初に出現する値の位置を返します。
indexOf()
値が見つからない場合、メソッドは-1を返します。
このindexOf()
方法では大文字と小文字が区別されます。
構文
string.indexOf(searchvalue, start)
パラメーター
Parameter | Description |
searchvalue | Required. The string to search for. |
start | Optional. The position to start from (default is 0). |
戻り値
タイプ | 説明 |
数 | 検索値が発生する最初の位置。 発生しない場合は-1。 |
文字列indexOf()と文字列search()の違い
メソッドはindexOf()
正規表現を検索できません。
はsearch()
開始位置引数を取ることができません。
ブラウザのサポート
indexOf()
ECMAScript1(ES1)機能です。
ES1(JavaScript 1997)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |