How do I swap substrings within a string?

后端 未结 5 565
无人共我
无人共我 2020-12-07 02:34

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

5条回答
  •  春和景丽
    2020-12-07 03:05

    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)

提交回复
热议问题