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

时间:2012-02-07 17:03:50

标签: javascript jquery

请说在我们的网站中我们可以使用以下网址:

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

最好的方法是什么?

4 个答案:

答案 0 :(得分:12)

Everybody stand back! I know regular expressions! 试试这个:

var my_location = window.location.toString().match(/\/\/[^\/]+\/([^\.]+)/)[1];

答案 1 :(得分:3)

您可以使用:

var result = window.location.pathname.replace(/\.[^\.\/]+$/, "").substr(1);

在javascript中,您可以通过window.location object访问网址的各个部分。

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的路径名组件,然后用""替换任何文件扩展名(有效删除它)并删除前导斜杠。

答案 2 :(得分:1)

我建议你这样做,

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

Result:
happy/ending/results/index.html

答案 3 :(得分:0)

比仅使用正则表达式更简洁:

var path = $('<a>', {href: 'http://google.com/foo/bar.py'})[0].pathname.replace(/\.(.+)$/,'')