Replace all in JavaScript

The JavaScript .replace() function will only replace the first instance if you use just two strings like this:

var text = 'This is the blog of Adriaan, the worst blog in the universe'
text.replace('blog', 'life') // 'This is the life of Adriaan, the worst blog in the universe'

So to replace all occurences of blog you can use:

text.replace(/blog/g, 'life')

But that is 30% slower than this:

text.split('blog').join('life')

Happy coding! – Found a mistake or a typo? Please submit a PR to my GitHub-repo.

Get my next post right in your inbox via Blogsend
(I don't get your email address so I can't spam you)

Like this post? Follow @adriaanvrossum on Twitter