Regular Expressions Basics
Replacing Patterns
Replace every matching word with a new value.
replace-pattern
`replace` can use a regular expression. The `g` flag repeats the replacement for every match instead of only the first match.
Replacing Patterns
replace_pattern.js
Replay: real traced execution (multi-file project)
const source = "red blue red";
const updated = source.replace(/red/g, "green");
console.log("source=" + source);
console.log("updated=" + updated);
const source = "red red";
const updated = source.replace(/red/g, "green");
console.log("source=" + source);
console.log("updated=" + updated);
const source = "blue red";
const updated = source.replace(/red/g, "green");
console.log("source=" + source);
console.log("updated=" + updated);
source ← red blue red, updated ← green blue green
1const source→ red blue red = "red blue red"; //@source="red red", "blue red"2const updated→ green blue green = sourcered blue red.replace(/red/g, "green");34console.log("source=" + sourcered blue red);5console.log("updated=" + updatedgreen blue green);outputsource=red blue red updated=green blue green
source ← red red, updated ← green green
1const source→ red red = "red red";2const updated→ green green = sourcered red.replace(/red/g, "green");34console.log("source=" + sourcered red);5console.log("updated=" + updatedgreen green);outputsource=red red updated=green green
source ← blue red, updated ← blue green
1const source→ blue red = "blue red";2const updated→ blue green = sourceblue red.replace(/red/g, "green");34console.log("source=" + sourceblue red);5console.log("updated=" + updatedblue green);outputsource=blue red updated=blue green