Regular Expressions: Replacing

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


We already saw how to check if a string contains a pattern.

We also saw how to extract parts of a string to an array, matching a pattern.

Let’s see how to replace parts of a string based on a pattern.

The String object in JavaScript has a replace() method, which can be used without regular expressions to perform a single replacement on a string:

"Hello world!".replace('world', 'dog') //Hello dog!
"My dog is a good dog!".replace('dog', 'cat') //My cat is a good dog!

This method also accepts a regular expression as argument:

"Hello world!".replace(/world/, 'dog') //Hello dog!

Using the g flag is the only way to replace multiple occurrences in a string in vanilla JavaScript:

"My dog is a good dog!".replace(/dog/g, 'cat') //My cat is a good cat!

Groups let us do more fancy things, like moving around parts of a string:

"Hello, world!".replace(/(\w+), (\w+)!/, '$2: $1!!!')
// "world: Hello!!!"

Instead of using a string you can use a function, to do even fancier things. It will receive a number of arguments like the one returned by String.match(RegExp) or RegExp.exec(String), with a number of arguments that depends on the number of groups:

"Hello, world!".replace(/(\w+), (\w+)!/, (matchedString, first, second) => {
  console.log(first);
  console.log(second);

  return `${second.toUpperCase()}: ${first}!!!`
})
//"WORLD: Hello!!!"

Lessons in this unit:

0: Introduction
1: Introduction
2: Anchoring
3: Match Items in Ranges
4: Matching a Range Item Multiple Times
5: Negating a Pattern
6: Meta Characters
7: Regular Expressions Choices
8: Quantifiers
9: Optional Items
10: Groups
11: Capturing Groups
12: Using match and exec Without Groups
13: Noncapturing Groups
14: Flags
15: Inspecting a Regex
16: Escaping
17: String Boundaries
18: ▶︎ Replacing
19: Greediness
20: Lookaheads
21: Lookbehinds
22: Unicode
23: Unicode Property Escapes
24: Examples