Bri Manning

JavaScript Global Replace Using Regular Expressions

January 19, 2012

I find the String.replace() functionality of JavaScript to be a bit more than annoying. This is because of one crucial reason.

When you do this:

'Hey there!'.replace('e', 'a');

coming from most backgrounds, you’d expect this:

'Hay thara!'

but you end up with this:

'Hay there!'

Wha?? Talk about running into debug issues and pulling your hair out.

The issue is that the default behavior is to just replace the first instance of a string. Personally, I’m not quite sure why this is the case, but the fact remains that it is. Now, another option is to use regular expressions. Let’s try:

'Hey there!'.replace(/e/, 'a');

Still, no dice. You get:

'Hay there!'

Egads!

However, if you do:

'Hey there!'.replace(/e/gi, 'a');

You’re then using the global regular expression replacement, so you get:

'Hay thara!'

Finally, just what we were looking for! So, note that anytime you do 'original string to search within'.replace(/string to look for/gi, 'string to replace with'), then you’ll end up with what you expected – a global replace-all function throughout the string.