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 occurrences 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.

Like this post? Follow @adriaandotcom on X