When you do this:
'Hey there!'.replace('e', 'a');
coming from most backgrounds, you’d expect this:
but you end up with this:
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:
However, if you do:
'Hey there!'.replace(/e/gi, 'a');
You’re then using the global regular expression replacement, so you get:
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.