Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace image src text with img

if a HTML code is

<div class="photos">
http://myweb.com/imgs/img1.jpg
https://myweb.com/imgs/img2.gif
http://myweb.com/imgs/img3.png
https://myweb.com/imgs/img4.bmp
</div>

how can you via jquery extract any url starting with either http:// OR https:// and ending with either .jpg .gif .png or .bmp and set them as images

<div class="photos">
<img src="http://myweb.com/imgs/img1.jpg"/>
<img src="https://myweb.com/imgs/img2.gif"/>
<img src="http://myweb.com/imgs/img3.png"/>
<img src="https://myweb.com/imgs/img4.bmp"/>
</div>
like image 630
Yusaf Khaliq Avatar asked Sep 28 '26 23:09

Yusaf Khaliq


2 Answers

This will do it ..

$('.photos').html(function(index, html){
    return html.replace(/(http\S+\.(jpg|gif|png|bmp))/gim,'<img src="$1" />');
});

Demo at http://jsfiddle.net/gaby/K2nQJ/

like image 87
Gabriele Petrioli Avatar answered Sep 30 '26 11:09

Gabriele Petrioli


Read out the contents of the div. Match the urls and replace the content of the div with the images:

$(".photos").each(function() {
    var images = $(this).html(),
        imgs = images.match(/https?:[^\s]+/g),
        html = "";
    for (var i=0; i<imgs.length; i++)
    {
        html += '<img src="'+imgs[i]+'"/>'+"\n";
    }
    $(this).html(html);
});

You can test it here: http://jsfiddle.net/inti/ez6WE/

Edit: an even better solution is to replace the urls in the original content with the images:

$(".photos").each(function() {
    var images = $(this).html(),
        imgs = images.match(/https?:[^\s]+/g);
    for (var i=0; i<imgs.length; i++)
    {
        images = images.replace(imgs[i], '<img src="'+imgs[i]+'"/>');
    }
    $(this).html(images);
});

Try it here: http://jsfiddle.net/inti/ez6WE/5/

Edit 2: to be sure to match only the images you want to display, the regex must be adjusted like this: /https?:[^\s]+\.(jpg|gif|png|bmp)/g (good point by @MrMisterMan)

like image 45
aorcsik Avatar answered Sep 30 '26 12:09

aorcsik