Search code examples
jqueryattributeswikipediasrc

Making sure the src attribute has http:


I am using this jquery script to import parts of wikipedia articles, but I have run into an issue where when this script is putting together an image tag, it strips out "http:" (or rather, it was't there in the first place?) from the src attribute. How can I ensure every img tag has http: at the beginning of the src attribute without adding another one if it is already there?

Here is what I am using:

https://gist.github.com/steren/704540

Specifically this is what adds the image in (but leaves out "http:"):

//get images of right side table
var rightTableImages = content.find('table a.image img');        
//append first image to main container  
wikiContainer.append($(rightTableImages).first().removeAttr('srcset').removeAttr('height').removeAttr('width').addClass("imageForArticle").wrap('<div class="wikipediaLogo"></div>').parent());

I have tried adding a class to the images by adding .addClass("imageForArticle") to the above and then tried this:

$('. imageForArticle').attr('src', function(index, src) {
return 'http:' + src;
});

But when I do that, if there are multiple articles in one page it sometimes adds an extra http: to one when I reload the page.


Solution

  • Try

    $('. imageForArticle').attr('src', function (index, src) {
        return (src.indexOf('http') == 0) ? src : 'http:' + src;
    });
    

    if src.indexOf('http') == 0 it starts with http than return same else add http:


    Or

    $('. imageForArticle').not('[src^="http"]').attr('src', function (index, src) {
        return 'http:' + src;
    });
    

    Exclude results with src strating from http $('. imageForArticle').not('[src^="http"]')