JavaScript の `replace()` メソッドは、文字列内の特定のパターンを検索し、別の文字列に置換するための便利な機能です。この記事では、`replace()` メソッドの基本的な使い方から応用まで、実践的なコード例とともに解説します。

replace() メソッドの基本的な使い方

`replace()` メソッドは、第1引数に検索するパターン(文字列または正規表現)、第2引数に置換する文字列を指定します。

const text = "Hello world";
const result = text.replace("world", "JavaScript");
console.log(result); // "Hello JavaScript"

重要な注意点:最初の一致のみを置換

デフォルトでは、`replace()` は最初に一致した部分のみを置換します。

const text = "apple apple apple";
const result = text.replace("apple", "orange");
console.log(result); // "orange apple apple"

すべての一致を置換する方法

すべての一致を置換するには、以下の2つの方法があります:

1. 正規表現とグローバルフラグを使用する

const text = "apple apple apple";
const result = text.replace(/apple/g, "orange");
console.log(result); // "orange orange orange"

2. replaceAll() メソッドを使用する(より新しい方法)

const text = "apple apple apple";
const result = text.replaceAll("apple", "orange");
console.log(result); // "orange orange orange"

大文字小文字を区別しない置換

正規表現の `i` フラグを使用することで、大文字小文字を区別せずに置換できます。

const text = "Hello HELLO hello";
const result = text.replace(/hello/gi, "hi");
console.log(result); // "hi hi hi"

関数を使用した高度な置換

`replace()` の第2引数に関数を指定することで、より複雑な置換処理が可能です。

const text = "cat and dog";
const result = text.replace(/cat|dog/g, (match) => {
    return match.toUpperCase();
});
console.log(result); // "CAT and DOG"

実践的な使用例

1. 日付形式の変換

const date = "2024-02-20";
const formatted = date.replace(/-/g, "/");
console.log(formatted); // "2024/02/20"

2. HTMLタグの除去

const html = "<p>Hello <strong>World</strong></p>";
const plainText = html.replace(/<[^>]*>/g, "");
console.log(plainText); // "Hello World"

3. 特定の文字のエスケープ

const text = "Hello (world)";
const escaped = text.replace(/[()]/g, "\\$&");
console.log(escaped); // "Hello \(world\)"

まとめ

  • `replace()` メソッドは文字列の置換に使用する基本的なメソッド
  • デフォルトでは最初の一致のみを置換
  • 正規表現とフラグを使用することで柔軟な置換が可能
  • より新しい `replaceAll()` メソッドですべての一致を置換可能
  • 関数を使用することで複雑な置換処理も実現可能

`replace()` メソッドは文字列操作の基本的なツールとして、多くの場面で活用できます。正規表現と組み合わせることで、より強力な文字列処理が実現できます。