Search code examples
javascriptif-statementgetjsonjpegfile-type

Appending a file type to a url with if - JS


I'm pulling from the Reddit API and populating a gallery using this:

$.getJSON("http://www.reddit.com/r/pics.json?jsonp=?",
function(data) {

    var imageurl1 = data.data.children[0].data.url;
    var imagecaption1 = data.data.children[0].data.title;;
    var commentlink1 = "http://www.reddit.com" + data.data.children[0].data.permalink;}

(I then feed this into an array)

90% of the time the permalink is a imgur.com jpg ... so I can feed the image straight into where I'm putting it. However, sometimes it's just the plain url, without the jpg bit at the end, breaking the image.

How do I add the .jpg extension ONLY if it isn't already there?

i.e. IF permalink = imgur.com/abc.jpg, do nothing, but if permalink = imgur.com/abc make it imgur.com/abc.jpeg ?

Any help much appreciated.


Solution

  • if(!imageurl1.match(/\.jpg$/))
      imageurl1 += '.jpg'