Regex to validate image url which may contains extension like 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
I'm expecting a regex which can give true if this extensions like jpg, jpeg, png, gif, webp are present in url.
I don't know what you'd like to do exactly but this should return 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>
:
fmt=jpeg
in middlefmt=jpeg
at endfmt=bmp
(unsupported format) 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:
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 fmt=
-- literal fmt=
parameter (this is to avoid false positives) (jpg|jpeg|png|gif|webp)
-- logical 'or' of supported file extensions (?=(&|$))
-- positive lookahead for either &
or end of string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.