I’m trying to match emotes and replace the emote characters with an image. I have the following:
var emotes ={
"laughing": Array(":))"),
"smile": Array(":o)",":-)",":)","=]","=)"),
"sick": Array(":-&")
};
Then I find the matches using:
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()));
});
The issues are:
- If the html equals “:) 🙂 🙂 🙂 :)” It is only replacing the first instance, not all
- Laughing, :)), it being picked up as a smile with a trailing )
- sick ends up outputting amp; html? “
<img src="/images/emoticons/face-sick.png" class="emoticonimg">amp;” at the end
Any RegEx experts able to lend a hand? Thanks
Oh, I see the issue — to do multiple replaces you have to use regex and add the
g(global) modifier at the end, which does the multiple replaces.In that case you’ll have to “regex-safe” your emoticons, which for you is basically escaping brackets with backslash, and escaping the backslash to get around javascript interpreting them.
To deal with issue 3 we replace the
:-&with:-&which is how it appears in HTML.Then to make the regex:
See http://jsfiddle.net/9D7Bk/7/
You’ll just have to be careful about:
[]()!.*+{}?^$in emoticons&->&,>to>etc in youremotes.