Last updated: Mar 4, 2024
Reading timeยท3 min

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
will return true if it does.
function isImage(url) { return /\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test(url); } // ๐๏ธ true console.log(isImage('https://bobbyhadz.com/photo.jpg')); // ๐๏ธ true console.log(isImage('https://bobbyhadz.com/photo.webp')); // ๐๏ธ false console.log(isImage('https://bobbyhadz.com/index.html'));

The
RegExp.test()
method returns true if the regular expression is matched in the string and
false otherwise.
/ / mark the beginning and end of the regular expression.We escaped the dot with a backslash. This is necessary because the dot has a special meaning in regular expressions.
The parentheses are called a capturing group and the pipe | symbol means "or",
e.g. jpg or jpeg or png.
The dollar sign $ matches the end of the input. In other words, the string has
to end with a .jpg extension.
This handles the edge case where the URL might contain an image extension anywhere else.
function isImage(url) { return /\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test(url); } // ๐๏ธ false console.log(isImage('https://example.jpeg.com'));

You might have to add more image extensions to the regular expression if your server hosts images with other extensions.
You can check if the string starts with https:// or http:// if you want to
make the regular expression stricter.
function isImage(url) { return /^https?:\/\/.+\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test( url, ); } // ๐๏ธ true console.log(isImage('https://bobbyhadz.com/photo.jpg')); // ๐๏ธ true console.log(isImage('https://bobbyhadz.com/photo.webp')); // ๐๏ธ false console.log(isImage('https://bobbyhadz.com/index.html'));

The caret ^ matches the beginning of the input.
The string has to start with http or https.
? matches the preceding item (the s character) zero or 1 times. This makes the s character 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.
If you ever need help reading a regular expression, check out this regular expression cheat sheet by MDN.
It contains a table with the name and the meaning of each special character with examples.
You can learn more about the related topics by checking out the following tutorials: