模块课程(2/4)
基本替换和“$1”
在 JavaScript 中,String.prototype.replace(regex, replacement) 执行
模式匹配并用给定的字符串替换每个匹配。使用 g
标记它替换所有匹配;没有它,只有第一个。 replaceAll
强制全局行为(并且需要正则表达式上的 g 标志)。
'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$.
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, $ for匹配项之前的所有文本,以及匹配项之后的所有文本的 $'` 。这样即使不编写 JS 代码也可以进行丰富的替换。
尝试一下
查找 YYYY-MM-DD 格式的每个日期,分为三组(年、月、日)。这样您就可以使用替换来获取 DD/MM/YYYY。
显示提示
在 (...) 捕获的三个组内将 \\d+ 替换为 \\d{4}、\\d{2}、\\d{2}。
3 次尝试后可用的解决方案
复习练习
找到“first last”作为两个命名组“nome”和“cognome”,因此您可以使用“$<cognome>, $<nome>”将其重写为“cognome, nome”。
显示提示
使用 (?<nome>\\w+) 和 (?<cognome>\\w+),并用 \\s+ 分隔。
3 次尝试后可用的解决方案
额外的挑战
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 次尝试后可用的解决方案