另一种方法:
function replaceEmoticons(text) {
var emoticons = {
':-)' : 'smile1.gif',
':)' : 'smile2.gif',
':D' : 'smile3.gif'
}, url = "http://www.domain.com/";
return text.replace(/[:\-)D]+/g, function (match) {
return typeof emoticons[match] != 'undefined' ?
'<img src="'+url+emoticons[match]+'"/>' :
match;
});
}
replaceEmoticons('this is a simple test :)');
编辑:@pepkin88提出了一个很好的建议,即基于表情符(emoticons)
对象的属性名称构建正则表达式。
这很容易实现,但我们必须转义元字符(meta-characters)以使其正常工作。
转义后的模式存储在数组中,稍后使用RegExp
构造函数构建正则表达式,基本上是将所有模式用|
元字符分隔并连接起来。
function replaceEmoticons(text) {
var emoticons = {
':-)' : 'smile1.gif',
':)' : 'smile2.gif',
':D' : 'smile3.gif',
':-|' : 'smile4.gif'
}, url = "http://www.domain.com/", patterns = [],
metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;
for (var i in emoticons) {
if (emoticons.hasOwnProperty(i)){
patterns.push('('+i.replace(metachars, "\\$&")+')');
}
}
return text.replace(new RegExp(patterns.join('|'),'g'), function (match) {
return typeof emoticons[match] != 'undefined' ?
'<img src="'+url+emoticons[match]+'"/>' :
match;
});
}
replaceEmoticons('this is a simple test :-) :-| :D :)');
emoticons
中的键值决定了正则表达式,那就更好了。 - pepkin88replace()
(类似于这个答案…) - 这将加速对该函数的重复调用。 - Tomalak