有一个包含以下某些子字符串的源字符串:
有必要将它们相应地替换为
我通过以下方式做到这一点
var output = input;
var re1 = /first/;
var re2 = /second/;
output = output.replace(re1, "third")
output = output.replace(re2, "forth")
问题是如何使用单个正则表达式来做到这一点?
您可能会做这样的事情;使用匿名函数:
var input = "This is the first... no second time that I tell you this!";
var result = input.replace(/first|second/g, function(m) {
switch(m)
{
case "first":
return "third";
case "second":
return "forth";
}
});
该变量m
将包含匹配项,并将其传递到switch
,如果需要,您可以在其中添加更多替换项。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句