Code Premix

How to Verify that an URL is an Image URL using JavaScript

📅July 12, 2022

In this short article, we will show you how to verify that an URL is an Image URL using JavaScript.

Here, we will use the Regular Expression to validate the image url using JavaScript.

Function

function checkURL(url) {
  if (typeof url !== 'string') return false;
  return (url.match(/\.(jpg|jpeg|gif|png)$/) != null);
}

Here we have validated the extension such as jpg, jpeg, gif, and png. This function will return the boolean value.

Output

checkURL('codepremix.com'); // Output: false
checkURL('https://xyz.com/abc.png'); // Output: true
checkURL('http://abc.com/xyz.gif'); // Output: true

In the upcoming article, we will show you how to check if an image exists from a URL.

That’s it for today.
Thank you for reading. Happy Coding..!!