js> var str = 'You are comparing apples to oranges.';
js> str.replace(/(apples|oranges)/g, '[$1]')
You are comparing [apples] to [oranges].
如果你喜歡一個功能,你可以簡單地養活的話數組:
function reg_quote(str, delimiter) {
return (str+'').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\'+(delimiter || '')+'-]', 'g'), '\\$&');
}
function mark_words(str, words) {
for(var i = 0; i < words.length; i++) {
words[i] = reg_quote(words[i]);
}
return str.replace(new RegExp('(' + words.join('|') + ')', 'g'), '[$1]')
}
演示:
js> mark_words(str, ['apples', 'oranges']);
You are comparing [apples] to [oranges].
js> mark_words(str, ['apples', 'You', 'oranges']);
[You] are comparing [apples] to [oranges].
如果你想它不區分大小寫,更換'g'
與'gi'
。
其實,對於正則表達式將是`(蘋果|桔子)`.. 。 – gnarf 2011-01-26 20:04:20