文字列の中から特定の文字やフレーズを探したいとき、JavaScriptのindexOf()メソッドを使うと簡単に検索できます。この記事では、indexOf()の基本的な使い方から実践的な活用例まで詳しく解説します。

indexOf()メソッドとは

indexOf()は、文字列の中から指定した文字列を検索し、最初に見つかった位置(インデックス)を返すメソッドです。文字列が見つからない場合は-1を返します。

基本的な使い方

const text = "Hello World";
const position = text.indexOf("World"); // 6を返す
const notFound = text.indexOf("xyz");   // -1を返す

検索開始位置の指定

第2引数に数値を指定すると、その位置から検索を開始できます:

const text = "Hello Hello World";
const position = text.indexOf("Hello", 2); // 6を返す

実践的な使用例

1. 文字列の存在確認

const text = "JavaScript Programming";
if (text.indexOf("JavaScript") !== -1) {
    console.log("JavaScriptが含まれています");
}

2. 複数回の出現位置を検索

const text = "apple orange apple banana apple";
let position = 0;
let count = 0;

while ((position = text.indexOf("apple", position)) !== -1) {
    count++;
    position += 1;
}
console.log(`appleは${count}回出現します`);

3. 大文字小文字を区別しない検索

const text = "Hello World";
const searchTerm = "HELLO";
const isIncluded = text.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1;

よくあるミス

1. 数値を直接検索しようとする

// ❌ 間違った使い方
const text = "123";
text.indexOf(123); // 文字列に変換する必要がある

// ✅ 正しい使い方
text.indexOf("123");

2. 正規表現を使用しようとする

// ❌ indexOf()は正規表現に対応していない
text.indexOf(/[0-9]/);

// ✅ 正規表現を使いたい場合はmatch()やsearch()を使用

代替手段

  • includes(): 文字列が含まれているかをブール値で返す
  • search(): 正規表現での検索に対応
  • match(): より複雑なパターンマッチングに対応

まとめ

indexOf()メソッドは:

  • 文字列内の検索に最適
  • シンプルで直感的な使い方
  • パフォーマンスが優れている
  • 基本的な文字列操作に十分な機能

文字列の検索で悩んだときは、まずindexOf()の使用を検討してみてください。より複雑な検索が必要な場合は、正規表現やその他のメソッドの使用を検討しましょう。