使用 JavaScript 检查 URL 是否为图像

检查 URL 是否是 JavaScript 中的图像

Check if a URL is an Image using JavaScript

要检查 url 是否为图像,请在test()与字符串末尾的图像扩展名匹配的正则表达式上调用该方法,例如.png
or
.jpgtest()方法将检查 url 是否以图像扩展名结尾,true如果是则返回。

索引.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'));

我们使用
RegExp.test
方法来检查正则表达式是否在字符串中匹配。

正斜杠/ /标记正则表达式的开始和结束。

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.

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 with 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 out this
regex cheatsheet
from MDN.

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.

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. 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.

这使我们能够匹配任何域名。

整个正则表达式匹配
https?://以点和图像扩展名开头和结尾的字符串。