How to change substrings inside a string?

I am trying to swap all occurrences of a pair of substrings within a given string.

For example, I can replace all occurrences of “coffee” with “tea” and all occurrences of “tea” in “coffee”.

This is the first thing I thought of:

var newString = oldString.replace(/coffee/g, "__").replace(/tea/g, "coffee").replace(/__/g, "tea");

It works most of the time, but if my input line contains the substring "__", it will not work properly.

I am looking for something that works regardless of the input that I give it, so I thought also and came up with the following:

var pieces = oldString.split("coffee");
for (var i = 0; i < pieces.length; i++)
  pieces[i] = pieces[i].replace(/tea/g, "coffee");
var newString = pieces.join("tea");

It works great, but it's kind of ugly and verbose. I tried to come up with something more concise, and I used the map function built into jQuery to come up with the following:

var newString = $.map(oldString.split("coffee"), function(piece) {
  return piece.replace(/tea/g, "coffee");
}).join("tea");

, , - , . - ?

+5
4

theString.replace(/(coffee|tea)/g, function($1) {
     return $1 === 'coffee' ? 'tea' : 'coffee';
});

( , , , )

+6

:

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); 

+2

. :

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

.

0

(), , -, , :

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

All Articles