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')
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')
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.
You seem to misunderstand what an OR does:
var ext = url.substr(url.length - 3 );
if (ext == 'gif' || ext == 'jpg' || ext == 'png') {
..
}
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.
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)
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.