How do I swap substrings within a string?

后端 未结 5 566
无人共我
无人共我 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:19

    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

提交回复
热议问题