Extract Public Id From Cloudinary URL

Viewed 483

I am using Cloudinary to host my media on the cloud for my NodeJS project. To delete an image from the Clodinary Cloud, I need to pass a Public Id for that image, to the Cloudinary API. I realised, Public ID is embedded into the url, how to I extract it out from the URL?

Because, I don't want to store my data in this format :

image : {
    url : `http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png`,
    publicId : `rsorl4rtziefw46fllvh`
}

Rather, I find it better to store it like this :

image : `http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png`
1 Answers

The solution to this problem is to implement a funciton which extracts the publicId for every URL passed in as argument.

Here's the function :

const getPublicId = (imageURL) => imageURL.split("/").pop().split(".")[0];

Edited after @loic-vdb 's suggestion

Explanation :

  1. It splits the string in an array using "/" as seperator.

    imageURL="http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png";

becomes,

imageURL = [ 'http:',
  '',
  'res.cloudinary.com',
  'cloud_name',
  'image',
  'upload',
  'v1647610701',
  'rsorl4rtziefw46fllvh.png' ]
  1. Next, pop the array (returns the last element of the array)

    imageURL = 'rsorl4rtziefw46fllvh.png';

  2. Now, split this string into array using "." as seperator, we get :

    imageURL = [ 'rsorl4rtziefw46fllvh', 'png' ]

  3. Finally select the 0th element that is our PublicId return that

    imageURL = 'rsorl4rtziefw46fllvh';

Related