メインコンテンツにスキップ
モジュール 7 · レッスン 2 / 4コース内の 26/32~10 min
モジュールのレッスン (2/4)

基本的な置換と `$1`

JavaScript では、String.prototype.replace(regex, replacement) は パターンに一致し、各一致を指定された文字列に置き換えます。 g を使用する すべての一致を置き換えるフラグ。それがなければ、最初だけです。 replaceAll グローバル動作を強制します (正規表現に g フラグが必要です)。

JS
'ciao mondo'.replace(/o/g, '0'); // "cia0 m0nd0"
'Mario Rossi'.replace(/(\w+) (\w+)/, '$2 $1'); // "Rossi Mario"

置換文字列内の参照

置換文字列内では、これらは特別です:

  • $1、$2、\u2026 -- 正規表現の 番号付きグループへの後方参照。
  • $<name> -- 名前付きグループへの後方参照。
  • $& -- 試合全体。
  • `$`` -- text before the match.
  • $' -- text after the match.
  • $$ -- a single literal $.
JS
const data = '2024-03-15';
data.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1');
// "15/03/2024"

Reformat the date by inverting the order. The regex has 3 groups, and in the replacement string you reference them as $1, $2__PROTECTED_INLINE _14__$3.

Special references in replacements

Besides $1 and $2, you can use $& to insert the whole matched text, $ 一致に先行するすべてのテキストと、それに続くすべてのテキストの$'`。これにより、JS コードを記述しなくても豊富な置換が可能になります。

試してみてください

運動#regex.m7.l2.e1
試行回数: 0読み込み中…

3 つのグループ (年、月、日) を使用して、YYYY-MM-DD 形式のすべての日付を検索します。このようにして、replace を使用して DD/MM/YYYY を取得できます。

エディターを読み込み中…
ヒントを表示

(...) でキャプチャされた 3 つのグループ内の \\d+ を \\d{4}、\\d{2}、\\d{2} に置き換えます。

3 回の試行後に解決策が利用可能になります

復習演習

運動#regex.m7.l2.e2
試行回数: 0読み込み中…

'first last' は 2 つの名前付きグループ `nome` と `cognome` として検索されるため、`$<cognome>, $<nome>` を使用してこれを `cognome, nome` に書き換えることができます。

エディターを読み込み中…
ヒントを表示

(?<nome>\\w+) と (?<cognome>\\w+) を \\s+ で区切って使用します。

3 回の試行後に解決策が利用可能になります

追加の課題

運動#regex.m7.l2.e3
試行回数: 0読み込み中…

Create a capture pattern to reverse the order of first and last name from `Lastname, Firstname` format to `Firstname Lastname`.

エディターを読み込み中…
ヒントを表示

Use two capture groups for last and first name; the replacement will be performed via $2 $1.

3 回の試行後に解決策が利用可能になります