Categories
JavaScript Answers

How to Verify that an URL is an Image URL with JavaScript?

Spread the love

Sometimes, we want to verify that an URL is an image URL with JavaScript.

In this article, we’ll look at how to verify that an URL is an image URL with JavaScript.

Verify that an URL is an Image URL with JavaScript

To verify that an URL is an image URL with JavaScript, we can create our own function and that checks the URL we want to verify against our own regex.

For instance, we can write:

const isImgLink = (url) => {
  if (typeof url !== 'string') {
    return false;
  }
  return (url.match(/^http[^\?]*.(jpg|jpeg|gif|png|tiff|bmp)(\?(.*))?$/gmi) !== null);
}

console.log(isImgLink('https://example.com/img.jpg'));
console.log(isImgLink('https://example.com/any-route?param=not-img-file.jpg'));
console.log(isImgLink('https://example.com/img.jpg?param=123'));

to create the isImgLink function that takes the url we want to check.

Then in the function, we check if url isn’t a string with the typeof operator.

If it’s not, we return false .

Otherwise, we call url.match to check against the pattern that matches image URLs.

We check for common image file extensions like jpg , jpeg , gif , png , tiff , and bmp .

The g flag checks the whole string.

We also check that there’re no dots after the extension with (?(.*)) .

Conclusion

To verify that an URL is an image URL with JavaScript, we can create our own function and that checks the URL we want to verify against our own regex.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *