我需要創建一個功能性,這將允許我解析一個文本,尋找匹配不同格式的表情符串。它可以是一個:)
類型表情符號或<dog>
(<dog>
)類型。 目前我的函數可以找到這兩種類型,但需要兩個不同的正則表達式完成這個任務,我想,使其在短短的一步。有任何想法嗎 ?正則表達式匹配各種類型的表情符號列表
活生生的例子:http://jsfiddle.net/rmQSx/5/
,代碼:
function replaceEmoticons(text) {
var emots1 = {
':)': 'smile.gif',
':(': 'sad.gif',
},
emots2 = {
'<dog>': 'dog.gif',
'<fly>': 'fly.gif'
},
regex1,regex2,p,re;
for(p in emots1){
regex1 = "["+p+"]{2}";
re = new RegExp(regex1, "g");
text = text.replace(re, function (match) {
return typeof emots1[match] != 'undefined' ?
'<img src="'+emots1[match]+'"/>' :
match;
});
}
for(p in emots2){
regex2 = "("+p+")(|$)";
re = new RegExp(regex2, "g");
text = text.replace(re, function(match) {
return typeof emots2[match] != 'undefined' ?
'<img src="'+emots2[match]+'"/>' :
match;
});
}
return text;
}
console.log(replaceEmoticons('this is <dog>b a<fly> simple test :) , ;) and more:):('));
的作品就像一個魅力 – mikeTa