从URL中删除协议、域名、域和文件扩展名

5

假设我们的网站可以有如下URL:

http://domainame.com/dir/one-simple-name.html
https://dmainame.com/mail/send.php
https://dmainame.com/mail/read

所以我希望能够检索到相关信息。
dir/one-simple-name
mail/send
mail/read

最佳实践是什么?


@Brad 那个答案再次返回扩展名。 - Toni Michel Caubet
如果那个回答不符合您的需求,请尝试其他 50 个重复项之一,或者询问如何通过 . 拆分字符串。 - Brad
4个回答

16

5
我建议通过以下方式来实现:

var url = "https://www.somegoodwebsite.com/happy/ending/results/index.html";
console.log(url.replace(/^.*\/\/[^\/]+/, '') ); 

;

Result:
happy/ending/results/index.html

4
你可以使用这个:
var result = window.location.pathname.replace(/\.[^\.\/]+$/, "").substr(1);

在JavaScript中,您可以通过window.location对象访问URL的各个部分。
window.location.href - the entire URL 
window.location.host - the hostname and port number - [www.sample.com]:80
window.location.hostname - the hostname - www.sample.com
window.location.pathname - just the path part - /search
window.location.search - the part of the URL after the ? symbol - ?q=demo

在您的情况下,您可以使用window.location.pathname,如果您需要从文件名中去掉文件扩展名,则可以使用一些额外的javascript来完成:
var result = window.location.pathname.replace(/\.[^\.\/]+$/, "").substr(1);

这行JavaScript代码将获取URL的路径名组件,然后用""替换任何文件扩展名(有效地删除它),并删除前导斜杠。

a = "https://dev59.com/8mDVa4cB1Zd3GeqPaidc"a.replace(/.[^./]+$/, "").substr(1);"ttp://stackoverflow.com/questions/9180511/remove-protocol-domainame-domain-and-file-extension-from-url" - Sheik797

0
比起仅使用正则表达式,更具有 jQuery 风格的方式是:
var path = $('<a>', {href: 'http://google.com/foo/bar.py'})[0].pathname.replace(/\.(.+)$/,'')

我尝试了这个,但只得到了一个脚本错误:“未捕获的类型错误:无法读取 null 的属性 '0'”。 - jfriend00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接