JavaScriptのreplaceとreplaceAll:文字列置換の使い方まとめ
JavaScript で文字列を置換するには replace() と replaceAll() を使います。2つの違いは「最初の1件だけ置換するか、すべて置換するか」です。
replace():最初の1件だけ置換
const str = 'hello world hello'
console.log(str.replace('hello', 'hi')) // 'hi world hello'
文字列を渡すと最初の1件だけ置換されます。
replaceAll():すべて置換
const str = 'hello world hello'
console.log(str.replaceAll('hello', 'hi')) // 'hi world hi'
replaceAll() はすべての一致箇所を置換します。Node.js 15 以降・Chrome 85 以降で使えます。
正規表現で置換する
replace() + /g フラグで全件置換
const str = 'hello world hello' console.log(str.replace(/hello/g, 'hi')) // 'hi world hi'
/g(global)フラグをつけると replace() でもすべて置換できます。
大文字・小文字を無視して置換
const str = 'Hello World HELLO' console.log(str.replace(/hello/gi, 'hi')) // 'hi World hi'
/i(case-insensitive)フラグで大文字・小文字を区別しません。
置換文字列に関数を使う
第2引数に関数を渡すと、マッチした文字列を加工して置換できます。
const str = 'hello world' // マッチした単語の先頭を大文字にする const result = str.replace(/\b\w/g, (char) => char.toUpperCase()) console.log(result) // 'Hello World'
replaceAll() の注意点
replaceAll() に正規表現を渡すときは /g フラグが必須です。フラグなしで渡すとエラーになります。
// ❌ TypeError: String.prototype.replaceAll called with a non-global RegExp argument 'hello'.replaceAll(/hello/, 'hi') // ✅ /g フラグが必要 'hello'.replaceAll(/hello/g, 'hi')
まとめ
| メソッド | 置換対象 | 備考 |
|---|---|---|
str.replace('old', 'new') |
最初の1件 | 文字列を渡す場合 |
str.replace(/old/g, 'new') |
すべて | 正規表現 + /g フラグ |
str.replaceAll('old', 'new') |
すべて | Node.js 15+ / Chrome 85+ |
str.replaceAll(/old/g, 'new') |
すべて | 正規表現には /g 必須 |
str.replace(/old/, (m) => ...) |
最初の1件 | 関数で加工 |