Check if a URL is an Image using JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20212 min read

Check if a URL is an Image in JavaScript #

To check if a url is an image, call the test() method on a regular expression that matches an image extension at the end of a string, e.g. .png or .jpg. The test() method will check if the url ends with an image extension and return true if it does.

index.js
function isImage(url) { return /\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test(url); } // ๐Ÿ‘‡๏ธ true console.log(isImage('https://example.com/photo.jpg')); // ๐Ÿ‘‡๏ธ true console.log(isImage('https://example.com/photo.webp')); // ๐Ÿ‘‡๏ธ false console.log(isImage('https://example.com/index.html'));

We used the RegExp.test method to check if a regular expression is matched in a string.

The forward slashes / / mark the beginning and end of the regular expression.

The dot has to be escaped, because it has a special meaning in regular expression, therefore we escape it using a backslash \..

The parenthesis are called a capturing group and the pipe | symbol means - or.

Either of the image extensions that are separated by pipe characters are a valid match, as long as they come after a dot and at the end of the string.

The dollar sign $ matches the end of the input, in other words the string has to end in a .jpg extension.

This handles the edge case where the url might contain an image extension anywhere else.

index.js
function isImage(url) { return /\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test(url); } // ๐Ÿ‘‡๏ธ false console.log(isImage('https://example.jpeg.com'));

If you ever need help reading a regular expression, check this regex cheatsheet from MDN out.

You might have to add more image extensions to the regular expression, if your server hosts images with other extensions.

If you want to make the regular expression more strict, you can check if the string starts with https:// or http://.

index.js
function isImage(url) { return /^https?:\/\/.+\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test(url); } // ๐Ÿ‘‡๏ธ true console.log(isImage('https://example.com/photo.jpg')); // ๐Ÿ‘‡๏ธ true console.log(isImage('https://example.com/photo.webp')); // ๐Ÿ‘‡๏ธ false console.log(isImage('https://example.com/index.html'));

The caret ^ matches the beginning of the input.

The string has to start with http or https.

The question mark ? matches the preceding item (the s character) zero or 1 times, in other words it makes it optional.

We used backslashes to escape the forward slashes that follow the https:// protocol.

The last thing we added is a dot and a plus. The dot . matches any single character and the plus + matches the preceding item one or more times.

This enables us to match any domain name.

In its entirety the regular expression matches strings that start with https?:// and end with a dot and an image extension.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee