Capstone: reformatting names
Everything from this batch comes together here. Capture groups (Phase 5)
pull pieces out of a match; .replace()'s replacement string can refer back
to them with $1, $2, and so on - so you can rebuild the matched text in a
different order , not just swap it for something fixed.
"Ada, Lovelace".replace(/(\w+), (\w+)/, "$2 $1") captures "Ada" as group
1 and "Lovelace" as group 2, then rebuilds the replacement as $2 followed
by $1: "Lovelace Ada". The pattern found the shape; the replacement
string reordered the pieces it captured.
Your task: write reformatName(str), converting a single "Last, First"
name to "First Last", and reformatNames(list), applying that same
reformat to every name in an array (reuse reformatName inside .map()).
You'll practice:
Referring to captured groups in a replacement string with $1/$2
Reusing a single-string regex function across a list with .map()
Show a hint
Show solution
Related reading: Using Regex for Real (and the Gotchas) →
Previous Next