wadie wadie - 1 year ago 38
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;
imgext = imgsrc.split('.').pop();
if(imgext != 'jpg' || imgext != 'jpeg' || imgext != 'gif'){
console.log("Unacceptable,add extension");
FinalURL = imgsrc + '.jpg';
else {

Answer Source

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.