Borislav Hadzhiev
Thu Nov 18 2021·2 min read
Photo by Alexander Popov
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.
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.
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.
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.
If you want to make the regular expression more strict, you can check if the
string starts with https://
or http://
.
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.