Search code examples
javascriptjqueryimagesrc

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>

Solution

  • 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/