如何在字符串中交换子字符串? [英] How do I swap substrings within a string?

查看:181
本文介绍了如何在字符串中交换子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试交换给定字符串中所有出现的一对子串。

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

例如,我可能想要将所有出现的coffee替换为茶和所有出现的茶和咖啡。

For example, I may want to replace all occurrences of "coffee" with "tea" and all occurrences of "tea" with "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 string contains the substring "__", it will not work properly.

无论我给出什么输入,我都在找一些有用的东西,所以我想了更多,并想出了这个:

I am looking for something that works regardless of what input I give it, so I thought some more and came up with this:

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

它工作正常,但它有点丑陋和冗长。我尝试提出更简洁的内容,并使用jQuery中内置的映射函数来实现以上:

It works fine but it is 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 this:

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

这是更好但我仍然觉得有一些非常简单的方法未能实现在我心里。这里有没有人知道更简单的方法?

That is better but I still have a feeling that there is some brilliantly simple method that is failing to come to my mind. Does anyone here know a simpler way?

推荐答案

怎么样

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)

这篇关于如何在字符串中交换子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆