序章

文字列内のテキストを置き換えることは、JavaScriptの一般的なタスクです。 この記事では、 replace テキストを置き換える正規表現。

注: Linux でgrepと正規表現を使用してテキストパターンを検索する方法の詳細な概要については、このコンパニオンチュートリアルにアクセスしてください。

前提条件

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

通常、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番目の例では、円記号をエスケープするために円記号を使用する必要はありません。

結論

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