KANAYO AUSTIN KANE KANAYO AUSTIN KANE - 7 months ago 30
Javascript Question

Replacing text with smiley image using Jquery

Please Guys, I am new to Jquery. I have been searching for a suitable help since last week but I can't find any. I want to replace a text with a smiley image using jquery but I have no idea how to run this. For example, I want this text "I am feeling

:happy;
" to be replaced with "I am feeling
<img src='happy_face.gif' />
" and "He is
:sick;
" to be replaced with "He is
<img src='sick.gif' />
".
Here is what I have gotten so far but it still displays the text instead of the image:

:) :(
<script src="js/jscript.js"></script>
<script>
var emotes = [
[':happy;', 'happy.gif'],
[':sick;', 'sick.gif']
];

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;
}


Thanks in advance

Answer

It is actually quite simple. You only need one line to find and replace string instances in the HTML: $("body").html($("body").html().replace(/:happy;/g,'<div class="happy-face"></div>'));

This sets $("body").html() to the $("body").html() with :happy; replaced with <div class="happy-face"></div>.

/:happy;/g is RegEx to find the string :happy; globally (g)

https://jsfiddle.net/heowqt1u/2/