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 :)');
CMS Jun 16 '10 at 17:09 2010-06-16 17:09
source share