Skip to content

Instantly share code, notes, and snippets.

@alankimo
Forked from DanWebb/imgURL.js
Created January 18, 2019 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alankimo/4ea7a8830b9d8072e3124abd23d5bec5 to your computer and use it in GitHub Desktop.
Save alankimo/4ea7a8830b9d8072e3124abd23d5bec5 to your computer and use it in GitHub Desktop.
Specify a size for a Shopify image asset url. Equivalent to the liquid image size filter: `{{ image | img_url: "medium" }}`
String.prototype.imgURL = function(size) {
// remove any current image size then add the new image size
return this
.replace(/_(pico|icon|thumb|small|compact|medium|large|grande|original|1024x1024|2048x2048|master)+\./g, '.')
.replace(/\.jpg|\.png|\.gif|\.jpeg/g, function(match) {
return '_'+size+match;
})
;
};
// example
'//cdn.shopify.com/s/files/1/0087/0462/products/shirt14.jpeg?v=1309278311'.imgURL('medium');
// outputs
'//cdn.shopify.com/s/files/1/0087/0462/products/shirt14_medium.jpeg?v=1309278311'
// alternatively, if you don't want to use a polyfil
function imgURL(src, size) {
// remove any current image size then add the new image size
return src
.replace(/_(pico|icon|thumb|small|compact|medium|large|grande|original|1024x1024|2048x2048|master)+\./g, '.')
.replace(/\.jpg|\.png|\.gif|\.jpeg/g, function(match) {
return '_'+size+match;
})
;
}
// example
imgURL('//cdn.shopify.com/s/files/1/0087/0462/products/shirt14.jpeg?v=1309278311', 'medium');
// outputs
'//cdn.shopify.com/s/files/1/0087/0462/products/shirt14_medium.jpeg?v=1309278311'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment