将多个字符串替换组合成一个语句?

时间:2014-01-12 16:49:28

标签: javascript regex

这就是我现在正在做的事情:

text = text.replace(/{{contact first}}/gi, contact.first)
    .replace(/{{contact last}}/gi, contact.last)
    .replace(/{{contact name}}/gi, contact.first + ' ' + contact.last);

有没有办法:

text = text.replace([
    /{{contact first}}/gi,
    /{{contact last}}/gi,
    /{{contact name}}/gi
], [
    contact.first,
    contact.last,
    contact.first + ' ' + contact.last
]);

2 个答案:

答案 0 :(得分:4)

var contact={first:'John',last:'Doe'}

var text='{{contact first}} blah blah {{contact last}} blah blah blah {{contact name}} blahblah';

text= text.replace(/{{contact (first|last|name)}}/gi, function(a, b){   
    return contact[b]|| contact.first+' '+contact.last;
});

text;

/*  returned value: (String)
John blah blah Doe blah blah blah John Doe blahblah
*/

答案 1 :(得分:3)

Javascript不支持,但您可以使用String#replace这样:

text = text.replace(/{{contact (first|last|name)}}/gi, function($0, $1) {
    if ($1 == "last") 
       return contact.last;
    else
       return contact.first;
});
相关问题