Replacing all matches in a string

When replacing a substring in a string, only the first match is replaced. If we want to replace all matches, we need to use a regular expression and tell it to match globally within the string.

// 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!'

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.