user2777052
user2777052

Reputation: 155

jquery replace text with image (for emoticons)

These two lines of code work perfectly -

var html = $this.find('pre').html().replace(':mellow:','<img src="http://i2.ifrm.com/html/emoticons/mellow.gif">');
$this.find('pre').html(html);

(It finds the string :mellow: and replaces it with a specific image.)

The difficulty I'm having is in trying to turn it into something where I don't have to repeat these two lines of code 50 or 60 times. (I'm at that beginner stage where you end up writing hundreds of lines of code when you could have done it in three.)

How would you turn the above into something that can handle multiple emoticon codes (e.g., :mellow:, :lol:, etc.) and figure out the corresponding image (which will have the same name as the code, minus the ::).

Pseudo code example -

var emoCodes = [
    ':mellow:', ':lol:', ':ninja:'
];          
var html = $this.find('pre').html().replace(+emoCodes+,'<img src="http://i2.ifrm.com/html/emoticons/+CorrespondingImage+.gif">');
$this.find('pre').html(html);

Alright, thanks.

Upvotes: 0

Views: 1823

Answers (2)

Johan Karlsson
Johan Karlsson

Reputation: 6476

This should do it:

var emoCodes = [
  ':mellow:', ':lol:', ':ninja:'
];
var $this = $("body");

emoCodes.forEach(function(code) {
  var image = '<img src="http://i2.ifrm.com/html/emoticons/' + code.replace(/:/g, "") + '.gif">';
  $this.find('pre').html(function(index, html) {    
    return html.replace(new RegExp(code, "g"), image);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>:mellow::mellow::lol::ninja:</pre>

Upvotes: 2

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You are on the right track with using an array, since you need to look for both the emoticon code and the corresponding image you can create an array of objects:

var emoCodes = [
    {code: ':mellow:', img: '<img src="http://i2.ifrm.com/html/emoticons/mellow.gif">'},
    {code: ':lol:', img: '<img src="http://i2.ifrm.com/html/emoticons/lol.gif">' },
    {code: ':ninja:', img: '<img src="http://i2.ifrm.com/html/emoticons/ninja.gif">' }
];  

Then loop through the array applying the code and img properties:

for(var i=0: i<emoCodes.length; i++) {
    var html = $this.find('pre').html().replace(RegExp(emoCodes[i].code,"g"),emoCodes[i].img);
    $this.find('pre').html(html);
}

This methods allows you to have any code apply to any image, even if the code is not embedded inside it's url.

Upvotes: 2

Related Questions