Global flag: find and replace all
str.replace(pattern, replacement) without the g flag stops after the
first match - the rest of the string is left untouched, even if the
pattern could match again later on. Add the g flag and .replace()
changes behavior: it swaps out every match it finds, in one pass.
This is the same g flag from the price-extraction capstone (Phase 7), but
paired with .replace() instead of .match() - there the goal was pulling
matches out , here it's swapping matches out for something else , like
redacting every phone number in a block of text with ***.
Your task: write redactFirstPhone(str), replacing only the first
phone number found in str with "***", and redactAllPhones(str),
replacing every phone number with "***". A phone number looks like
555-123-4567 - three digits, a dash, three digits, a dash, four digits.
You'll practice:
Seeing .replace() stop after the first match without the g flag
Adding g to replace every occurrence in one call
Show a hint
Show solution
Related reading: Using Regex for Real (and the Gotchas) →
Previous Next