用于验证图像url的Regex,该url可能包含jpeg、jpg、gif、png等扩展。
我在用
/\.(jpg|jpeg|png|gif|webp)(\?.*)*$/i
但对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
来说却是假的
我期待一个正则表达式,如果像jpg、jpeg、png、gif、webp这样的扩展出现在url中,它就能给出真结果。
发布于 2022-11-18 15:23:09
您可以使用此regex测试URL参数fmt=<format>
fmt=jpeg
in fmt=jpeg
at fmt=bmp
(不支持的格式)H 210F 211
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));
});
输出:
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
对regex的解释:
\b
-- word boundaryfmt=
-文字fmt=
参数(这是为了避免错误的fmt=
-支持的文件extensions(?=(&|$))
的逻辑‘或’- &
或string的正向查找。
发布于 2022-11-18 01:52:48
我不知道您到底想做什么,但是应该返回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));
https://stackoverflow.com/questions/74479668
复制相似问题