// 19/11/2020 - by @th0rgall - transform HubSpot Image URLs to responsive variants

// simplified function assuming we have valid input, and we only use the width
function getResponsiveHubSpotImageURL(baseUrl, width) {
 
  // Check if URLs are oftypes 1 and 2 or similar (domain doesn't matter)
  // Extract the Portal ID and image name (can include slashes)
  let hubProperties = /https:\/\/[^\/]+\/hubfs\/(\d+)\/(.+)/.exec(baseUrl);
  if (!hubProperties) {
    console.warn(
      "HubSpot's Image Resizing API endpoint has changed, possibly. Contact this site's developer and share this URL:",
      baseUrl
    );
    // return the original URL in case it did not match the pattern
    return baseUrl;
  } else {
    return `https://f.hubspotusercontent40.net/hub/${hubProperties[1]}/hubfs/${hubProperties[2]}?width=${width}&name=${hubProperties[2]}`;
  }
}

// TEST CASES

console.log(
  getResponsiveHubSpotImageURL(
    "https://cdn2.hubspot.net/hubfs/123456/my_image_name.jpg", 400
  )
);
// prints 'https://f.hubspotusercontent40.net/hub/123456/hubfs/my_image_name.jpg?width=400&name=my_image_name.jpg'

console.log(
  getResponsiveHubSpotImageURL(
    "https://f.hubspotusercontent40.net/hubfs/123456/my_image_folder/my_image_name.jpg", 600
  )
);
// prints 'https://f.hubspotusercontent40.net/hub/123456/hubfs/my_image_folder/my_image_name.jpg?width=600&name=my_image_folder/my_image_name.jpg'

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.