[英]Regex to validate image url which may contains extension like jpeg, jpg, gif, png
Regex to validate image url which may contains extension like jpeg, jpg, gif, png用于验证图像 url 的正则表达式,它可能包含 jpeg、jpg、gif、png 等扩展名
I'm using我正在使用
/\.(jpg|jpeg|png|gif|webp)(\?.*)*$/i
but it gives false for https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&fmt=jpeg&qlt=80&.v=1603399121000
但它给出了错误的
https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&fmt=jpeg&qlt=80&.v=1603399121000
I'm expecting a regex which can give true if this extensions like jpg, jpeg, png, gif, webp are present in url.如果 url 中存在像 jpg、jpeg、png、gif、webp 这样的扩展,我期待一个可以给出 true 的正则表达式。
I don't know what you'd like to do exactly but this should return true
:我不知道你到底想做什么,但这应该返回
true
:
var text = "https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&fmt=jpeg&qlt=80&.v=1603399121000"; const regex = new RegExp(/(\W)(jpg|jpeg|png|gif|webp)(\W)/); console.log(regex.test(text));
You can use this regex to test for URL parameter fmt=<format>
:您可以使用此正则表达式来测试 URL 参数
fmt=<format>
:
fmt=jpeg
in middlefmt=jpeg
在中间fmt=jpeg
at endfmt=jpeg
fmt=bmp
(unsupported format)fmt=bmp
(不支持的格式) const regex = /\bfmt=(jpg|jpeg|png|gif|webp)(?=(&|$))/; [ 'https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&fmt=jpeg&qlt=80&.v=1603399121000', 'https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&qlt=80&.v=1603399121000&fmt=jpeg', 'https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&fmt=bmp&qlt=80&.v=1603399121000', ].forEach(url => { console.log(url + ' => ' + regex.test(url)); });
Output: Output:
https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&fmt=jpeg&qlt=80&.v=1603399121000 => true
https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&qlt=80&.v=1603399121000&fmt=jpeg => true
https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&hei=3072&fmt=bmp&qlt=80&.v=1603399121000 => false
Explanation of regex:正则解释:
\b
-- word boundary \b
-- 单词边界fmt=
-- literal fmt=
parameter (this is to avoid false positives) fmt=
-- 文字fmt=
参数(这是为了避免误报)(jpg|jpeg|png|gif|webp)
-- logical 'or' of supported file extensions (jpg|jpeg|png|gif|webp)
-- 支持的文件扩展名的逻辑“或”(?=(&|$))
-- positive lookahead for either &
or end of string (?=(&|$))
-- 对&
或字符串结尾的正向预测
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.