Search code examples
javascriptjqueryemoticons

Find and delete text, then insert an image with jquery or javascript


im trying to replace text with an image using jquery or javascript. for example

<div id="log">
<p>this is a :) happy face</p>
<p>this is a :( sad face</p>
<p>these are :/ x( :P other faces</p>
</div>

ive attempted a few things but either i end up replacing the entire string or the browser does not render the image and instead displays the html

this is a <img src="happy.png"> face

this is for a chat application im messing with and im fairly new so if you can include some explanation in your code thatd help :)


Solution

  • Could look like (using jQuery):

    $('div#log').find('p').html(function( html ) {
        return html.replace(':)', '<img src="happy.png"/>');
    });
    

    Obivously this should get a little more sophisticated. I could imagine a lookup object where you link strings to images, for instance:

    var myMap = {
        '\\:\\)': 'happy.png',  // need to escape those for regex
        '\\:\\(': 'sad.png',
        '\\:\\/': 'other.png'
    };
    
    $('div#log').find('p').html(function( _, html ) {
        for(var face in myMap) {
            html = html.replace( new RegExp( face, 'g' ), '<img src="' + myMap[ face ] + '"/>' );
        }
        return html;
    });