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>
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/
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With