How do I swap substrings within a string?

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

    Based on @alexander-gessler's answer, but with support for dynamic inputs.

    (While potentially opening the door to code injection.)

    function swapSubstrings(string, a, b) {
      return string.replace(
        new RegExp(`(${a}|${b})`, "g"),
        match => match === a ? b : a
      )
    }
    

提交回复
热议问题