Javascript 如何在没有站点名称、没有斜杠、合并的文本中显示url?

Javascript 如何在没有站点名称、没有斜杠、合并的文本中显示url?,javascript,jquery,Javascript,Jquery,如何在没有站点名称、没有斜杠、合并的文本中显示url 站点url示例:sitename.site/job/cvs/index.html 如何获取文本:“jobcvs”{ 如果(index!==pathnameSplit.length-1)返回a+b; 归还 }) } console.log(getJoinedPathname('https://sitename.site/job/cvs/index.html')) console.log(getJoinedPathname('https://si

如何在没有站点名称、没有斜杠、合并的文本中显示url

站点url示例:sitename.site/job/cvs/index.html


如何获取文本:“jobcvs”

您可以执行以下操作:

const url = "sitename.site/job/cvs/index.html"
const parts = url.split("/");
parts.shift();
parts.pop();
const res = parts.join('');

我假设您希望能够获得任何URL的连接路径。如果是这种情况,您可以使用获取路径名,将其拆分为“/”并将除文件名以外的所有内容重新连接在一起并返回结果。下面是我想到的。这可能会简化为一行,但为了便于阅读,我保留了较长的形式

函数getJoinedPathname(url){ const urlObj=新URL(URL); 常量pathnameSplit=urlObj.pathname.split(“/”) 返回pathnameSplit.reduce((a,b,index)=>{ 如果(index!==pathnameSplit.length-1)返回a+b; 归还 }) } console.log(getJoinedPathname('https://sitename.site/job/cvs/index.html')) console.log(getJoinedPathname('https://sitename.site/job/cvs/anotherpath/index.html')) console.log(getJoinedPathname('https://sitename.site/job/cvs/1/2/3/index.html')) console.log(getJoinedPathname('https://sitename.site/job/cvs/index.html?name=test')) console.log(getJoinedPathname('https://stackoverflow.com/questions/64055299/how-to-display-url-in-text-without-site-name-without-slash-merged'))
console.log(getJoinedPathname(window.location.href))您可以从当前页面中创建一个示例吗?我已根据要求添加了该示例。请注意,您可以使用window.location.href获取当前url,但由于代码的执行方式,它没有加入并返回空白的路径。我不确定我是否理解。什么不起作用?console.log(getJoinedPathname(window.location.href))它确实起作用,但代码段运行在具有不同URL()的iframe中。此URL没有可加入的路径,因为它只有一级深度。