Javascript正则表达式用表情符号替换文本 [英] Javascript regex replace text with emoticons
本文介绍了Javascript正则表达式用表情符号替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要通过表情符号替换;)
或:p
等文本,但我无法创建正则表达式为了检测这个。现在我只能检测到:wink:
I need to replace text like ;)
or :p
by emoticon but I can't create a regex in order to detect this. Now i can detect only like :wink:
function replaceEmoticons(text) {
var emots = {
";)": "wink",
":)": "xxx",
":p": "xxx",
};
return text.replace(/:(.*?):/g, function (match) {
return typeof emots[match] != 'undefined' ?
'<img src="http://localhost:8080/'+emots[match]+'.png"/>' :
match;
});
}
有什么好的正则表达式?
What is the good regex for that ?
推荐答案
请尝试以下操作。但是,在制作正则表达式时,您应该在表情符号中转义特殊字符(和)。
Try the following.However, you should escape the special characters ( and ) in your smileys when making the regexes.
//帮助函数转义正则表达式中的特殊字符
//helper function to escape special characters in regex
function RegExpEscape(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function replaceEmoticons(text) {
var emoticons = {
':)' : 'smile.gif',
':(' : 'sad.gif',
';)' : 'wink.gif'
}
var result = text;
var emotcode;
var regex;
for (emotcode in emoticons)
{
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正则表达式用表情符号替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文