跳转到主要内容
eLearner.app
模块 7 · 第 2 课(共 4)课程中的26/32~10 min
模块课程(2/4)

基本替换和“$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

锻炼#regex.m7.l2.e1
尝试:0加载中...

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.

正在加载编辑器...
显示提示

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

3 次尝试后可用的解决方案

Review exercise

锻炼#regex.m7.l2.e2
尝试:0加载中...

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

正在加载编辑器...
显示提示

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

3 次尝试后可用的解决方案

Additional challenge

锻炼#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 次尝试后可用的解决方案