How to replace all occurrences of a string in JavaScript

October 9, 2014 at 1:28 PMMadestro

I was working on a template in JavaScript and needed to replace all occurrences of a particular place holder string within it.

As it turns out, using the ubiquitous string.replace() function does not work as it only replaces the first occurrence.

As it turns out the following pattern can be used to achieve this:

str.split(search).join(replacement);

So, let's say I have the following variable:

var template = "This is just some hard text because it's hard to read but not so hard to write";

And I want to replace all occurrences of "hard" with "soft". I would do:

template = template.split("hard").join("soft");

The result is:

"This is just some soft text because it's soft to read but not so soft to write"

Pretty clever piece of code. It works like a charm. I wish I had thought of it myself... Cry

The original article where I found this solution can be seen here.

Posted in: JavaScript

Tags: