简体   繁体   中英

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:)

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

Have you tried doing this?

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

var p = $('#my').html();
var r = p.replace(':)', '<img src="happy.jpg">');
$('#my').html(r);

Fiddle here: http://jsfiddle.net/PuDMx/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM