我正在尝试匹配表情并用图像替换表情符号。我有以下内容:
var emotes ={
"laughing": Array(":))"),
"smile": Array(":o)",":-)",":)","=]","=)"),
"sick": Array(":-&")
};
然后我使用以下方式找到匹配项:
function emoticons(html){
for(var emoticon in emotes){
for(var i = 0; i < emotes[emoticon].length; i++){
// Replace the emote with the image
html = html.replace(emotes[emoticon][i],"<img src=\""+icon_folder+"/face-"+emoticon+".png\" class=\"emoticonimg\" />","g");
}
}
return html;
}
return this.each(function(){
$(this).html(emoticons($(this).html()));
});
问题是:
<img src="/images/emoticons/face-sick.png" class="emoticonimg">amp;
”在最后任何RegEx专家都能伸出援助之手吗?感谢
答案 0 :(得分:1)
哦,我看到了问题 - 要做多次替换,你必须使用正则表达式并在末尾添加g
(全局)修饰符,这将替换多个。
在这种情况下,你必须“正则表达式”保护你的表情符号,这对你来说基本上是用反斜杠转义括号,并转义反斜杠来解释它们的javascript。
要处理问题3,我们将:-&
替换为:-&
,这就是它在HTML中的显示方式。
var emotes ={
"laughing": Array(":\\)\\)"),
"smile": Array(":o\\)",":-\\)",":\\)","=\\]","=\\)"),
"sick": Array(":-&")
};
然后制作正则表达式:
var re = new RegExp(emotes[emoticon][i],"g"); // <-- replace all occurences
html = html.replace(re,"<img src=\""...);
请参阅http://jsfiddle.net/9D7Bk/7/
你必须要小心:
[]()!.*+{}?^$
&
- &gt;您&
中的>
,>
至emotes
等。答案 1 :(得分:0)
试试这个:
jQuery.fn.emoticons = function (icon_folder) {
/* emoticons is the folder where the emoticons are stored*/
var icon_folder = icon_folder || "http://www.dcc.uchile.cl/~skreft/emoticon/emoticons";
//var settings = jQuery.extend({emoticons: "emoticons"}, options);
/* keys are the emoticons
* values are the ways of writing the emoticon
*
* for each emoticons should be an image with filename
* 'face-emoticon.png'
* so for example, if we want to add a cow emoticon
* we add "cow" : Array("(C)") to emotes
* and an image called 'face-cow.png' under the emoticons folder
*/
var emotes = {
"laughing": Array(":))"),
"smile": Array(":o)", ":-)", ":)", "=]", "=)"),
"sick": Array(":-&")
};
function emoticonsReplace(str) {
var ret = str.replace(/\&/g, "&").replace(/\:\)\)|\:\o\)|\:\-\)|\:\)|\=\]|\=\)|\:\-\&/g, function (match) {
switch (match) {
case ":))":
return '<img src="' + icon_folder + '/face-laughing.png" class="emoticonimg" />';
break;
case ":o)":
case ":-)":
case ":)":
case "=]":
case "=)":
return '<img src="' + icon_folder + '/face-smile.png" class="emoticonimg" />';
break;
case ":-&":
return '<img src="' + icon_folder + '/face-sick.png" class="emoticonimg" />';
break;
}
});
return ret;
}
return this.each(function () {
var $this = $(this);
$this.html(emoticonsReplace(decodeURIComponent($this.html())));
});
};
我把它编辑成一个完整的解决方案。它对我有用:)
我将它重新用于你的jsFiddle。当我跑步时,它有效。