[英]javascript - get substring after a word and before an extension
我有以下格式的 url:
https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg
如何從中提取hokhqmcmmkveqhxtr0nb
? 所以提取dealetePosts
和.jpg
之間的內容
字符串 position,后跟 substring 可以,但有更簡單的方法嗎?
這是我到目前為止所擁有的並且有效,但這是最好的方法嗎?
const publicID = dealPic.substring(
dealPic.indexOf("dealetePosts/") + 13,
dealPic.lastIndexOf(".jpg")
);
我使用 substring function 和正則表達式刪除任何擴展名(jpg、png 等),即使 dealetePosts 更改為任何其他名稱,它也能正常工作
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))
您可以使用類似拆分和彈出方法的方法斜杠“/”和“。” 特點。 那就是如果你總是期待相同類型的 url。
let url = "https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg";
let key = url.split("/").pop().split(".")[0];
console.log(key);
您可以使用正則表達式並在一行中完成所有這些操作:
const url = "https://res.cloudinary.com/xyzzz/image/upload/v1673615977/dealetePosts/hokhqmcmmkveqhxtr0nb.jpg" const filename = /.*\/(.*)\.jpg/.exec(url)[1]; console.log(filename)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.