本文介绍了在正则表达式/Javascript中将字符交换为另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做类似的事情:

var a = "This is an A B pattern: ABABA";  
a.replace("A", "B");  
a.replace("B", "A");  

并返回:
=>这是一个B A模式:BABAB"
代替:
=>这是一个A A模式:AAAAA"

and have it return:
=> "This is an B A pattern: BABAB"
instead of:
=> "This is an A A pattern: AAAAA"

我首先想到的是做类似的事情:

My first thought is to do something like:

a.replace("A", "improbablePattern");  
a.replace("B", "A");  
a.replace("improbablePattern", "B");  

我该怎么做呢?

推荐答案

您可以将函数传递给 .replace() 调用与两个匹配的正则表达式,如下所示:

You could pass a function to your .replace() call with the regex that matches both, like this:

var a = "This is an A B pattern: ABABA";  
a = a.replace(/(A|B)/g, function(a, m) { return m == "A" ? "B" : "A"; });
alert(a);​ //alerts "This is an B A pattern: BABAB"

您可以在此处尝试

这篇关于在正则表达式/Javascript中将字符交换为另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 14:23