JavaScript replace() and replaceAll(): Text Updates
Quick answer
Replacement methods produce a new string. A string pattern in replace changes only its first occurrence, while replaceAll changes every nonoverlapping occurrence.
How it works
Use text.replace(search, replacement) or text.replaceAll(search, replacement). A string replacement interprets special $ sequences; for example $& inserts the match. A callback returns literal replacement text. Regex patterns are covered next; a regex passed to replaceAll must have the global flag.
const text = "red red blue";console.log(text.replace("red", "green"));console.log(text.replaceAll("red", "green"));Expected output in Node.js:
green red bluegreen green blueA literal search changes first or all matches respectively.
const text = "item";console.log(text.replace("item", "[$&]"), text);Expected output in Node.js:
[item] item$& inserts the matched text; the original remains unchanged.
Common mistakes
Keep the returned value. Replacing a string does not change the original, and replacement is not HTML sanitization.
Practice
Replace repeated separators in a label; compare first-only and all-occurrence behavior.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript replace() and replaceAll(): Text Updates — Knowledge Check
Apply the taught concept and predict the output.
How many occurrences does replace change with a string search argument?
Which replacement form returns literal text without expanding dollar substitutions?
What happens to a string stored in a const binding after replaceAll is called?
What is the exact console output in JavaScript replace() and replaceAll(): Text Updates example 1?
const text = "red red blue";console.log(text.replace("red", "green"));console.log(text.replaceAll("red", "green"));What is the exact console output in JavaScript replace() and replaceAll(): Text Updates example 2?
const text = "item";console.log(text.replace("item", "[$&]"), text);