我需要创建一个功能,这将允许我解析文本以寻找不同格式的表情符号字符串的匹配项。它可以是:)
类型表情符号,也可以是<dog>
( <dog>
) 类型。目前我的函数可以找到这两种类型,但需要两个不同的正则表达式来完成这个任务,我想一步完成。有任何想法吗 ?
jsfiddle 的实时示例: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:):('));