Javascript - 如何从 location.href 中删除域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6945429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - how to remove domain from location.href
提问by Marta
I need to remove the domain name from location.href using Javascript. I have links like: http://localhost/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO
and I need to have links without http://localhost
and in future without it's real domain name.
我需要使用 Javascript 从 location.href 中删除域名。我有这样的链接:http://localhost/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO
我需要在没有http://localhost
和将来没有真实域名的情况下建立链接。
I will use those trimed links in Javascript function so I would like to trim it also in Javascript.
我将在 Javascript 函数中使用那些修剪过的链接,所以我也想在 Javascript 中修剪它。
I have tried: window.location.href.split('/')[2];
but I could only get domain form it. And I want to get rid of domain.
我试过:window.location.href.split('/')[2];
但我只能从它获得域。我想摆脱域。
Any help here much appreciated!
非常感谢这里的任何帮助!
回答by Vivin Paliath
Use window.location.pathname
. This gives you the path relative to the host. See herefor more details.
使用window.location.pathname
. 这为您提供了相对于主机的路径。请参阅此处了解更多详情。
For any arbitrary URL, assuming that the variable url
contains your URL, you can do:
对于任意 URL,假设变量url
包含您的 URL,您可以执行以下操作:
url = url.replace(/^.*\/\/[^\/]+/, '')
回答by Dan Davies Brackett
Rather than doing string manipulation on window.location.href
, you can use the other properties of window.location
. In your case, you want the pathname, the search and the hash:
window.location.href
您可以使用 的其他属性,window.location
而不是对 进行字符串操作。在您的情况下,您需要路径名、搜索和哈希:
console.log(window.location.pathname + window.location.search + window.location.hash);
回答by alnorth29
I posted this on your other question as a comment but I might as well add it here too. You can use a replace with a regex, like this:
我将此作为评论发布在您的另一个问题上,但我也不妨将其添加到此处。您可以使用正则表达式替换,如下所示:
location.href.replace(/.*\/\/[^\/]*/, '')
location.href.replace(/.*\/\/[^\/]*/, '')