-2

I'm trying to detect images in javascript, this is what I thought would work but it isn't. How can I do it correctly?

if (url.substr(url.length - 3 ) == 'gif' || 'jpg' || 'png')
chendriksen
  • 1,026
  • 6
  • 16
  • 30

4 Answers4

2

You can't use the || in that fashion. You'd have to re-write the if statement as:

var lastThree = url.substr(url.length - 3);
if(lastThree == 'gif' ||
   lastThree == 'jpg' ||
   lastThree == 'png')
{
    // do something
}

Or you could use an array (which I would prefer personally):

if(['gif','jpg','png'].indexOf(url.substr(url.length - 3)) > -1)
{
    // do something
}

You should also use the toLowerCase() method on the URL substring, since some image files might end in JPG or GIF for example.

numX
  • 830
  • 7
  • 24
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

You seem to misunderstand what an OR does:

var ext = url.substr(url.length - 3 );
if (ext == 'gif' || ext == 'jpg' || ext == 'png') {
   ..
}
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
1

You can use a regular expression:

if (/gif|jpg|png/i.test(url.substr(url.length - 3 )))

Note that jpg can also be jpeg, gif might be giff and there is also tiff and other formats. And the extension is not reliable to determine a file format.

Edit

And as Cookie Monster suggests, you can save a bit of typing using:

/(gif|jpg|png)$/i.test(url)

and just add extras as required:

/(gif|jpg|jpeg|jfif|png|tiff|raw|bmp|svg)$/i.test(url)
RobG
  • 142,382
  • 31
  • 172
  • 209
0

You need to provide the complete condition after ||

    var src = url.substr(url.length - 3 );
    if (src === 'gif' || src === 'jpg' || src === 'png')

=== is used to check the value and type.

Vinoth
  • 657
  • 6
  • 12