A pot
Rose
A pot
Blackberry
A pot
Rose
A pot
Blackberry
A pot
Rose
123
let garden = "Rose\tBlackberry\t
Rose\tBlackberry\t
Rose";
123456
garden = garden
.replace(//gi, "Blackberry");
Lesson 28 / 42

Lesson task •

Replace all the roses with blackberry.

flag g continued

Replaces all the matches, not only the first match

To make the regular expression to replace all the occurrences, not only the first, we have to add flag g to the regular expression:

123
console.log("foo foo foo".replace(/foo/i, "bar")) // bar foo foo 
console.log("foo foo foo".replace(/foo/gi, "bar")) // bar bar bar 
console.log("foo1 foo2 foo3".replace(/foo(\d+)/gi, "$1")) // 1 2 3 

If your regular expression includes capturing group, it will be reevaluated for every match:

1
console.log("foo1 foo2 foo3".replace(/foo(\d+)/gi, "$1")) // 1 2 3