I am trying to swap all occurrences of a pair of substrings within a given string.
For example, I can replace all occurrences of “coffee” with “tea” and all occurrences of “tea” in “coffee”.
This is the first thing I thought of:
var newString = oldString.replace(/coffee/g, "__").replace(/tea/g, "coffee").replace(/__/g, "tea");
It works most of the time, but if my input line contains the substring "__", it will not work properly.
I am looking for something that works regardless of the input that I give it, so I thought also and came up with the following:
var pieces = oldString.split("coffee");
for (var i = 0; i < pieces.length; i++)
pieces[i] = pieces[i].replace(/tea/g, "coffee");
var newString = pieces.join("tea");
It works great, but it's kind of ugly and verbose. I tried to come up with something more concise, and I used the map function built into jQuery to come up with the following:
var newString = $.map(oldString.split("coffee"), function(piece) {
return piece.replace(/tea/g, "coffee");
}).join("tea");
, , - , . - ?