I have a url in javascript, set as a variable. Like:
var imageurl='example.com/test/real/image.jpg';
I am trying to recognize if this is an image url or not (ending with jpeg, jpg, gif, png etc.).
I tried using charAt but it did not work.
What’s the best way to return a 1 if it is an image url and 0 otherwise using javascript?
The file extension (if there even is one) has no bearing on whether a URL points to a resource that is an image type. That is only a convention used by some people for static resources.
Looking at the file extension can be enough if you only need it as a general heuristic:
but for accuracy the only way to find out if a URL points to an image is to fetch that URL and see what comes back. Typically you’d do that by issuing a HEAD request to the URL and seeing if the headers in the response contain
Content-Type: image/something.You can’t do that directly from browser JavaScript, but what you can do is create an image element and see if loads OK: