Replacing all matches in a string
JavaScriptAll snippets in this category →
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!"
// 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!"