Replace all in JavaScript
16 Dec 2015 - Help improve this postThe 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.