0

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.

svick
  • 236,525
  • 50
  • 385
  • 514
user2219915
  • 289
  • 3
  • 7
  • 19
  • Why do you need that? URLs like `//example.com/` are [perfectly valid](https://en.wikipedia.org/wiki/Protocol_relative_URL). – svick Feb 24 '14 at 16:26

2 Answers2

2

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"]')

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

Try this:

$('. imageForArticle').attr('src', function (index, src) {
    return (src.indexOf('http') < 0) ? src : 'http:' + src;
});
Furquan Khan
  • 1,586
  • 1
  • 15
  • 30