How do I swap substrings within a string?

后端 未结 5 553
无人共我
无人共我 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)

    0 讨论(0)
  • 2020-12-07 03:11

    Use a map (an object) to define what replaces what and then a function to tap into the map:

    D:\MiLu\Dev\JavaScript :: type replace.js
    function echo(s) { WScript.Echo(s) }
    var
    map = { coffee: "tea", tea: "coffee" },
    str = "black tea, green tea, ice tea, teasing peas and coffee beans";
    echo( str.replace( /\b(tea|coffee)\b/g, function (s) { return map[s] } ) );
    
    D:\MiLu\Dev\JavaScript :: cscript replace.js
    black coffee, green coffee, ice coffee, teasing peas and tea beans
    
    0 讨论(0)
  • 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
      )
    }
    
    0 讨论(0)
  • 2020-12-07 03:16

    Close. Consider this:

    var newString = oldString.replace("tea|coffee", function(match) {
        // now return the right one, just a simple conditional will do :)
    });
    

    Happy coding.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题