MENU
Grouping and Back References
During replacements, within a match, you can group the characters with (), and back-reference them with $1-$9.
Additionally,$& references the whole match.$` references the left context.$' references the right context.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var s = "abc";
console.log(s.replace(/a(.)(.)/,"$2")); // c
console.log(s.replace(/a/,"$&$&")); // aabc
console.log(s.replace(/b/,"$`")); // aac
console.log(s.replace(/a/,"$'")); // bcbc
</script></body><html>
You can name each capture group by starting the () group with ?<name>.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
const r =
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;const d = r.exec("2020-07-29");/*d.groups.year === "2020"d.groups.month === "07"d.groups.day === "29"d[0] === "2020-07-29"d[1] === "2020"d[2] === "07"d[3] === "29"*/let {groups:{year,month,day}} = d; // destructuringconsole.log(year,month,day); // 2020 07 29
</script></body><html>