[英]Regex matching list of emoticons of various type
我需要創建一個功能,這將允許我解析文本以尋找不同格式的圖釋字符串的匹配項。 它可以是:)
類型的圖釋,也可以是<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;
}
使用|
你可以這樣做:
re = new RegExp(smiley1|smiley2|...|smileyN);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.