I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Replacing all matches in a string

Posted on

By default, only the first match is replaced when using .replace() on a string. If we want to replace all matches, we need to use a regular expression and tell it to match globally within the string.

If we add a g after the regular expression’s closing slash, all matching substrings will be replaced.

// if the first parameter is a string, only the first match is replaced
"Pika pika!".replace("ka", "dgey") // ⇒ "Pidgey pika!"
 
// we can write the pattern as a regular expression, which achieves the same
"Pika pika!".replace(/ka/, "dgey") // ⇒ "Pidgey pika!"
 
// with the additional `g`-flag, all matches (globally) are replaced
"Pika pika!".replace(/ka/g, "dgey") // ⇒ "Pidgey pidgey!"
// if the first parameter is a string, only the first match is replaced
"Pika pika!".replace("ka", "dgey") // ⇒ "Pidgey pika!"
 
// we can write the pattern as a regular expression, which achieves the same
"Pika pika!".replace(/ka/, "dgey") // ⇒ "Pidgey pika!"
 
// with the additional `g`-flag, all matches (globally) are replaced
"Pika pika!".replace(/ka/g, "dgey") // ⇒ "Pidgey pidgey!"
Debug
none
Grid overlay