jQuery: inserting emoticons

In this post I'm going to show you how to insert emoticons using jQuery and the JavaScript replace() function. We're going to take into account only three types of emoticons, namely a happy face (:-)), a sad face (:-() and a winking face (;-)). These emoticons have been directly inserted in the markup as the text content of a given element. Each emoticon will be replaced by the corresponding inline image using a regular expression pattern. Here's the jQuery code:

var emoticons = {

  smile: '<img src="path/smile.gif" />',
  sad: '<img src="path/sad.gif" />',
  wink: '<img src="path/wink.gif" />'


};

var patterns = {

  smile: /:-\)/gm,
  sad: /:-\(/gm,
  wink: /;-\)/gm


};

$(document).ready(function() {


  $('p').each(function() {
  
    var $p = $(this);
    var html = $p.html();
    
    $p.html(html.replace(patterns.smile, emoticons.smile).
    replace(patterns.sad, emoticons.sad).
    replace(patterns.wink, emoticons.wink));  
  
  });
});

The former object literal, named emoticons, contains the inline images for each emoticon, while the latter, named patterns, contains the regular expression patterns used to match the emoticons. We store the current HTML content of each element in a variable and the we call the jQuery's html() method by passing to it the replacements obtained with the replace() function. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: inserting emoticons”

Leave a Reply

Note: Only a member of this blog may post a comment.