2014-01-12 112 views
0

這是我現在在做什麼:將多個字符串替換爲一個語句?

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

回答

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 
*/ 
+0

不錯,我放棄了這個權利,它縮短了我的代碼相當多。 'Chrome 31.0.1650(Mac OS X 10.9.1):執行41/41 SUCCESS(0.575秒/ 0.021秒)' –

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; 
}); 
相關問題