Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何交换字符串中的子字符串?_Javascript_Regex_String - Fatal编程技术网

Javascript 如何交换字符串中的子字符串?

Javascript 如何交换字符串中的子字符串?,javascript,regex,string,Javascript,Regex,String,我试图交换给定字符串中一对子字符串的所有匹配项 例如,我可能想用“tea”替换所有出现的“coffee”,用“coffee”替换所有出现的“tea” 这是我想到的第一件事: var newString = oldString.replace(/coffee/g, "__").replace(/tea/g, "coffee").replace(/__/g, "tea"); 它在大多数情况下都能工作,但是如果我的输入字符串包含子字符串“_x”,它将无法正常工作 我正在寻找一种无论我投入多少都能起作

我试图交换给定字符串中一对子字符串的所有匹配项

例如,我可能想用“tea”替换所有出现的“coffee”,用“coffee”替换所有出现的“tea”

这是我想到的第一件事:

var newString = oldString.replace(/coffee/g, "__").replace(/tea/g, "coffee").replace(/__/g, "tea");
它在大多数情况下都能工作,但是如果我的输入字符串包含子字符串“_x”,它将无法正常工作

我正在寻找一种无论我投入多少都能起作用的东西,所以我想了很多,并得出了以下结论:

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");
var newString = $.map(oldString.split("coffee"), function(piece) {
  return piece.replace(/tea/g, "coffee");
}).join("tea");
这是更好的,但我仍然有一种感觉,有一些辉煌的简单的方法,是没有出现在我的脑海中。这里有人知道更简单的方法吗?

接近。考虑这一点:

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

那怎么办

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

(我个人认为交换咖啡和茶是犯罪行为,但那是你的事)

你可以使用以下功能:

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

使用贴图(对象)定义替换对象,然后使用函数点击贴图:

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

基于@alexander gessler,但支持动态输入

(同时可能打开代码注入的大门。)

函数交换字符串(字符串、a、b){
返回字符串.replace(
新的RegExp(`(${a}|${b})`,“g”),
匹配=>匹配===a?b:a
)
}

如果一个字符串是另一个字符串的子字符串,请小心。先放长一点的。(并明显避开任何特殊字符)