wadie wadie - 3 months ago 7
Javascript Question

Adding image extension when there isn't one

Using the following script, I am going through every img source I have on the page, retrieving the extension and if there is no returned string, or not a know image type then I add .jpg

For some reason the if statement is true every time regardless of the extension.

$(document).ready(function() {
$(".main_img").each(function() {
imgsrc = this.src;
console.log(imgsrc);
imgext = imgsrc.split('.').pop();
$.trim(imgext);
console.log(imgext);
if(imgext != 'jpg' || imgext != 'jpeg' || imgext != 'gif'){
console.log("Unacceptable,add extension");
FinalURL = imgsrc + '.jpg';
}
else {
console.log(imgext);
}
});
});

Answer

Easy fix for a bug in your code.

Just change the OR conditions to AND conditions and it will work.

Change this part:

if(imgext != 'jpg' || imgext != 'jpeg' || imgext != 'gif')

to this:

if(imgext != 'jpg' && imgext != 'jpeg' && imgext != 'gif')

It was not working because imgext will always be not equal to 3 different values simultaneously as suggested when using OR conditions in this case. Therefore, it will always come true. With AND, it will only accept if it is not equal to the value of either of the three. Should work.