Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - How do I swap substrings within a string?

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...