Replace the list of emoticons with your images

I have an array with:

emoticons = { ':-)' : 'smile1.gif', ':)' : 'smile2.gif', ':D' : 'smile3.gif' } 

then I have a variable with text.

 var text = 'this is a simple test :)'; 

and variable with website url

 var url = "http://www.domain.com/"; 

How to write a function that replaces characters with your images?

The result of the <img> should be:

 <img src="http://www.domain.com/simple2.gif" /> 

(I need to combine the url with the image name).

READ! Very important!

+14
javascript emoticons
Jun 16 '10 at 17:03
source share
3 answers

Another approach:

 function replaceEmoticons(text) { var emoticons = { ':-)' : 'smile1.gif', ':)' : 'smile2.gif', ':D' : 'smile3.gif' }, url = "http://www.domain.com/"; // a simple regex to match the characters used in the emoticons return text.replace(/[:\-)D]+/g, function (match) { return typeof emoticons[match] != 'undefined' ? '<img src="'+url+emoticons[match]+'"/>' : match; }); } replaceEmoticons('this is a simple test :)'); // "this is a simple test <img src="http://www.domain.com/smile2.gif"/>" 

Edit: @ pepkin88 made a really good suggestion, create a regex based on the property names of the emoticons object.

This is easy to do, but we need to avoid metacharacters if we want this to work properly.

Escaped patterns are stored in an array, which is later used to build a regular expression using the RegExp constructor, basically connecting all patterns separated by a metacharacter | .

 function replaceEmoticons(text) { var emoticons = { ':-)' : 'smile1.gif', ':)' : 'smile2.gif', ':D' : 'smile3.gif', ':-|' : 'smile4.gif' }, url = "http://www.domain.com/", patterns = [], metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g; // build a regex pattern for each defined property for (var i in emoticons) { if (emoticons.hasOwnProperty(i)){ // escape metacharacters patterns.push('('+i.replace(metachars, "\\$&")+')'); } } // build the regular expression and replace return text.replace(new RegExp(patterns.join('|'),'g'), function (match) { return typeof emoticons[match] != 'undefined' ? '<img src="'+url+emoticons[match]+'"/>' : match; }); } replaceEmoticons('this is a simple test :-) :-| :D :)'); 
+33
Jun 16 '10 at 17:09
source share
 for ( smile in emoticons ) { text = text.replace(smile, '<img src="' + url + emoticons[smile] + '" />'); } 
+4
Jun 16 '10 at 17:07
source share

Using a regex with an array of find replace elements works well.

 var emotes = [ [':\\\)', 'happy.png'], [':\\\(', 'sad.png'] ]; function applyEmotesFormat(body){ for(var i = 0; i < emotes.length; i++){ body = body.replace(new RegExp(emotes[i][0], 'gi'), '<img src="emotes/' + emotes[i][1] + '">'); } return body; } 
0
Sep 10 '10 at 19:46
source share



All Articles