JavaScript

String Replace in JavaScript

Today, I had the need to do a String.Replace in JavaScript. I thought, “surely, this is an easily solved problem”. It turns out that I was both right and wrong.

A quick DuckDuckGo search brought back that I could do something like this:

var input = "I hate Fridays.  Fridays are the worst!";
var output = input.replace("Fridays", "Mondays");

I would expect the value of output to be “I hate Mondays. Mondays are the worst!”. But it isn’t. Instead, the value is “I hate Mondays. Fridays are the worst!”, because the replace method will only replace the first instance of the match.

The first solution that I found to this was to modify the code to use a regular expression, which the replace method also takes. All you have to do is include the RegEx and the “g” flag to make the replacement global. That would make the code look like this:

var input = "I hate Fridays.  Fridays are the worst!";
var output = input.replace(/Fridays/g, "Mondays");

This does give us the correct output of “I hate Mondays. Mondays are the worst!”, but if this were to be a reusable method or a pattern throughout an application, getting the correct RegEx can be tricky to debug or come back to later. Not everyone is a RegExpert. That’s why the next solution that I found was ingenious and was the one that I ended up going with.

In this code, you split the string on your “outgoing” string, and join it back together again with your “incoming” string. That would look like this:

var input = "I hate Fridays.  Fridays are the worst!";
var output = input.split("Fridays").join("Mondays");

That gives us our correct output of “I hate Mondays. Mondays are the worst!”. This method can be slower in some browsers (This JSPerf test has Split/Join as coming out ~40% slower in Chrome), but if you aren’t doing this several hundred times in a loop, I think the readability and maintainability of the Split/Join way makes this easy to do.

2 comments String Replace in JavaScript

Brad says:

Pete,
This is not my code, but I use it…
String.Format is a method that I use frequently in the .net world. JS is missing that method. Here is a prototype for string.format that has come in handy…

// based on code from:
// http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery
String.prototype.format = function () {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{' + i + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};

Can be used like:
var foo = '{0} drives {1}. {2} should consider driving {3}'.format('Jeff', 'an Audi', 'Honda');

Jeff says:

var foo = ‘{0} needs to double check {1}, because it {2}. Also, I have {3} for sale!’.format(‘Brad’, ‘his example’, ‘does not work’, ‘an Audi’);

Leave a Reply

Your email address will not be published. Required fields are marked *