Home > Software design >  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

Time:11-19

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.

CodePudding user response:

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));

CodePudding user response:

You can use this regex to test for URL parameter fmt=<format>:

  • first example: fmt=jpeg in middle
  • second example: fmt=jpeg at end
  • third example: fmt=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= text
  • (jpg|jpeg|png|gif|webp) -- logical 'or' of supported file extensions
  • (?=(&|$)) -- positive lookahead for either & or end of string
  • Related