Skip to main content
eLearner.app
Module 7 · Lesson 2 of 426/32 in the course~10 min
Module lessons (2/4)

Basic replace and `$1`

In JavaScript, String.prototype.replace(regex, replacement) performs a pattern match and replaces each match with the given string. With the g flag it replaces all matches; without it, only the first. replaceAll forces the global behavior (and requires the g flag on the regex).

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

References in the replacement string

Inside the replacement string, these are special:

  • $1, $2, \u2026 -- backreference to the numbered group of the regex.
  • $<name> -- backreference to the named group.
  • $& -- the entire match.
  • `$`` -- 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, $3.

Special references in replacements

Besides $1 and $2, you can use $& to insert the whole matched text, $ for all text preceding the match, and$'` for all text following it. This allows rich replacements even without writing JS code.

Try it

Exercise#regex.m7.l2.e1
Attempts: 0Loading…

Find every date in the YYYY-MM-DD format with three groups (year, month, day). This way you could use replace to obtain DD/MM/YYYY.

Loading editor…
Show hint

Replace \\d+ with \\d{4}, \\d{2}, \\d{2} inside three groups captured with (...).

Solution available after 3 attempts

Review exercise

Exercise#regex.m7.l2.e2
Attempts: 0Loading…

Find 'first last' as two named groups `nome` and `cognome`, so you could rewrite it as `cognome, nome` using `$<cognome>, $<nome>`.

Loading editor…
Show hint

Use (?<nome>\\w+) and (?<cognome>\\w+) separated by \\s+.

Solution available after 3 attempts

Additional challenge

Exercise#regex.m7.l2.e3
Attempts: 0Loading…

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

Loading editor…
Show hint

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

Solution available after 3 attempts