I am trying to swap all occurrences of a pair of substrings within a given string.
For example, I may want to replace all occurrences of \"coffee\" with \"tea\" and
You can use a function:
var str = "I like coffee more than I like tea"; var newStr = str.replace(/(coffee|tea)/g, function(x) { return x === "coffee" ? "tea" : "coffee"; }); alert(newStr);
Running example