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