I have url in the following format:
https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg
How to extract hokhqmcmmkveqhxtr0nb
from this? So extract contents between dealetePosts
and .jpg
String position, followed by substring would work but is there an easier way?
This is what I have so far and works but is this the best way?
const publicID = dealPic.substring(
dealPic.indexOf("dealetePosts/") + 13,
dealPic.lastIndexOf(".jpg")
);
I use the substring function and a regex to remove any extension (jpg, png, etc) and it'works even if dealetePosts changed to anyother name
const test = "https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg"
function substr(str = ""){
const lastIndexSlash = str.lastIndexOf("/") + 1
return str.substring(lastIndexSlash, str.length).replace(/\.[^/.]+$/, "");
}
console.log(substr(test))
You can use something like a split and pop method method slash "/" & "." character. Thats if you are always expecting the same type of url.
let url = "https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg";
let key = url.split("/").pop().split(".")[0];
console.log(key);
You can use a regular expression and do all of this in a one-liner:
const url = "https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg" const filename = /.*\/(.*)\.jpg/.exec(url)[1]; console.log(filename)
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.