繁体   English   中英

javascript - 在一个词之后和分机号之前得到 substring

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM