JavaScriptで文字列のすべてのインスタンスを置き換える方法

提供:Dev Guides
移動先:案内検索

序章

文字列内のテキストを置き換えることは、JavaScriptの一般的なタスクです。 この記事では、replaceと正規表現を使用してテキストを置き換える方法について説明します。

前提条件

単一インスタンスの置き換え

通常、JavaScriptのString replace()関数は、文字列内で最初に見つかったインスタンスのみを置き換えます。

app.js

const myMessage = 'this is the sentence to end all sentences';
const newMessage = myMessage.replace('sentence', 'message');
console.log(newMessage); // this is the message to end all sentences

この例では、sentenceの最初のインスタンスのみが置き換えられました。

複数のインスタンスの置き換え

JavaScriptですべてのインスタンスを置き換える場合は、/g演算子を使用して正規表現を使用する必要があります。

app.js

const myMessage = 'this is the sentence to end all sentences';
const newMessage = myMessage.replace(/sentence/g, 'message');
console.log(newMessage); // this is the message to end all messages

今回は両方のインスタンスが変更されます。

インライン/gの使用に加えて、RegExpオブジェクトのコンストラクター関数を使用できます。

app.js

const myMessage = 'this is the sentence to end all sentences';
const newMessage = myMessage.replace(new RegExp('sentence', 'g'), 'message');
console.log(newMessage); // this is the message to end all messages

特殊文字の置き換え

-/\^$*+?.()|[]{})のような特殊文字を置き換えるには、バックスラッシュを使用してそれらをエスケープする必要があります。

これが例です。 文字列this\-is\-my\-urlが与えられた場合、すべてのエスケープされたダッシュ(\-)をエスケープされていないダッシュ(-)に置き換えましょう。

これはreplace()で実行できます。

app.js

const myUrl = 'this\-is\-my\-url';
const newUrl = myMessage.replace(/\\-/g, '-');
console.log(newUrl); // this-is-my-url

または、new Regexp()を使用します。

app.js

const myUrl = 'this\-is\-my\-url';
const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-');
console.log(newUrl); // this-is-my-url

この2番目の例では、円記号をエスケープするために円記号を使用する必要はありません。

結論

この記事では、単一のインスタンス、複数のインスタンスを置き換える方法、および文字列を特殊文字で処理する方法について説明しました。