我需要创建一个功能,它允许我解析文本以寻找不同格式的表情符号字符串的匹配项。它可以是 :)
输入表情符号,或 <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:):('));
最佳答案
我很确定您不需要在每个 for
开头做的有趣的事情循环修改正则表达式。摆脱它,没有什么能阻止您将这两个集合合并在一起。
但是,您应该转义特殊字符 (
和 )
在制作正则表达式时在你的笑脸中。此外,我建议使正则表达式搜索不区分大小写,以便 <dog>
和 <DOG>
都匹配。
//helper function to escape special characters in regex
function RegExpEscape(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function replaceEmoticons(text) {
var emots = {
':)' : 'smile.gif',
':(' : 'sad.gif',
'<dog>': 'dog.gif',
'<fly>': 'fly.gif'
}
var result = text;
var emotcode;
var regex;
for (emotcode in emots)
{
regex = new RegExp(RegExpEscape(emotcode), 'gi');
result = result.replace(regex, function(match) {
var pic = emots[match.toLowerCase()];
if (pic != undefined) {
return '<img src="' + pic + '"/>';
} else {
return match;
}
});
}
return result;
}
关于javascript - 正则表达式匹配各种类型的表情列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7317299/