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
What about
theString.replace(/(coffee|tea)/g, function($1) { return $1 === 'coffee' ? 'tea' : 'coffee'; });
(Personally I think it's a crime to swap coffee and tea, but that's your business)