根据正则表达式搜索结果替换单词

时间:2013-01-30 08:32:06

标签: javascript regex replace

我正试图找出正则表达式。我是相当新的,我想知道我是否可以用几行代码来完成以下操作。我试图避免在这里使用switch语句,所以我提出了执行以下操作的想法:

首先,让我解释一下这将做什么:获取一个字符串并用方法中已存在的变量替换键。像这样:

var a = 'item a',
    b = 'item b',
    string = '@a@ and @b@ have been replaced!',
    regex = /\@[a|b]\@/g;

 //now somehow replace this conditionally

 return string.replace(regex, this[replacerResut]);

输出将是这样的: item a and item b have been replaced!

不确定是否可能,但很想知道这样做的方法。有两个以上的局部变量,所以你可以看到为什么我不想使用开关,而我的新人说这就是我要做的!所以我知道这是错的。我正在尝试编写多态代码。谢谢你的帮助!

3 个答案:

答案 0 :(得分:4)

有可能,因为Javascript String#replace支持回调,但您应该收集一个对象的替换(获取var a的值知道"a"是不可能干净的方式):

var replacement={
      a : 'item a',
      b : 'item b'
    },
    string = '@a@ and @b@ have been replaced!',
    regex = /\@([ab])\@/g; //note the added capturing group


 return string.replace(regex, function(whole, key){
   return replacement[key];
 });

或者:

var a = 'item a',
    b = 'item b',
    string = '@a@ and @b@ have been replaced!',
    regex = /\@[ab]\@/g; 


 var replacement = {"@a@":a, "@b@":b};
 return string.replace(regex, function(whole){
   return replacement[whole];
 });

旁注:

您的正则表达式@[a|b]@将匹配@a@@b@,还会匹配@|@。使用替换(@(a|b)@或字符组(@[ab]@)。不要将它们混淆在一起。

答案 1 :(得分:2)

Jan Dvorak的回答是前进的方向。就像附录一样,通过使用替换对象一个闭包对象,他提供的代码甚至可以成为“cleaner”,因此可以在replace调用返回后进行GC编辑:

string.replace(expression, (function()
{
    var replacement = {a: 'item a',
                       b: 'item b'};
    return function(match)
    {//the actual callback
        return replacement[match];
    };
}()));//IIFE
//console.log(replacement);//undefined, can't be referenced anymore and may be flagged for GC

你不需要这么做,但你知道:即使你不能在JS中进行实际的内存管理,你也可以影响旗帜&通过封闭和范围扫除垃圾收集器......

答案 2 :(得分:1)

如果它们不是使用window的局部变量,可以这样做(虽然我称之为邪恶):

string.replace(regex, function (match, group) {
    return window[group];
});

如果可以的话,将它们放在一个对象中,字符串匹配为键,替换为值。

我推荐这个正则表达式:

regex = /@(\w+?)@/g;

http://jsfiddle.net/p4uvW/

相关问题