2

I am using web scraper api to get title, image and description of different websites. The thing I want to do is to get images with a specific format.. e.g. only get images that has jpg format extension .. I am trying to do that using js with if else.. here is the code and is not working

if(!(image.src == '[src*=".jpg"]')){
    console.log('No pic')
  }else{
    image.src = data.image;
  }
Adam.shw
  • 21
  • 2

3 Answers3

1

I would just do something like this:

if(!image.src.includes('jpg')) {
  console.log('No pic');
} else {
  image.src = data.image;
}

You could probably add an || !image.src.includes('.jpeg') to harden it up a little bit.

Or (as mentioned in the comments) simply querySelectorAll for all of the jpg image elements then you don't need this check above at all:

const imageElements = document.querySelectorAll('[src*=".jpg"]');
maxshuty
  • 9,708
  • 13
  • 64
  • 77
0

You can use contains for that:

if(!(image.src.contains("jpg")){
    console.log('No pic')
 }else{
    image.src = data.image;
}
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
0

It's a little difficult to know without understanding the API you are using, but generally you would want to be checking the MIME type of the file / image (if the API gives you that option). In your specific case the MIME type would be images/jpeg.

This question / answers may help - JS and type.match as file mime type - need advice

atchett
  • 16
  • 3