如何在JavaScript中获取不带任何参数的URL?


175

如果我使用:

alert(window.location.href);

我得到的一切都包括查询字符串。有没有一种方法可以获取主URL部分,例如:

http://mysite.com/somedir/somefile/

代替

http://mysite.com/somedir/somefile/?foo=bar&loo=goo

Answers:


280

这是可能的,但是您必须从location对象手动构建它:

location.protocol + '//' + location.host + location.pathname

14
请注意,您不需要提供location.protocol,因为所有现代浏览器(包括IE6)都会自动继承当前协议。即:'//' + location.host + location.pathname
JonnyReeves 2012年

10
@JonnyReeves如果在当前文档中使用它,那是对的:很好。在某些情况下可能有必要,例如将URL输出为纯文本。
lonesomeday '02

1
@lonesomeday您的回复暗示这是唯一的方法,并非如此。
Oddman '16

5
它缺少端口,因此这将返回错误的页面结果http://www.example.com:8080/asdf.html?foo=bar
izogfif

3
您可以使用来保存一些字符location.origin,我相信这也可以解决@izogfif的问题。
Coderer

170

每个答案都相当复杂。这里:

var url = window.location.href.split('?')[0];

即使一个?不存在,它将仍然返回第一个参数,它将是您的完整URL减去查询字符串。

它也与协议无关,这意味着您甚至可以将其用于ftp,itunes.etc等内容。


39
万一您需要卸下锚钉window.location.href.split(/[?#]/)[0];
Bahattin Ungormus 2015/09/17

实际上每一个答案是颇为曲折
穆罕默德

@mehmet,如果您有更简单的方法,那就大耳朵:)
Oddman

1
@Oddman,我绝对不记得我在想什么的话,但我想这可能是一个肯定的说法:))
穆罕默德

为什么(如果是)此答案比标记为接受的答案好?
Vishal--JAVA--CQ

16

indexOf

var url = "http://mysite.com/somedir/somefile/?aa";

if (url.indexOf("?")>-1){
url = url.substr(0,url.indexOf("?"));
}

5
var url = "tp://mysite.com/somedir/somefile/?foo=bar&loo=goo"    

url.substring(0,url.indexOf("?"));

3
假设该参数已定义。更好的是url.split('?')[0]
actimel 2014年

5

您可以使用正则表达式: window.location.href.match(/^[^\#\?]+/)[0]


5

您可以concat originpathname,如果存在端口,例如example.com:80,也将包括在内。

location.origin + location.pathname

2

如果您查看文档,则可以仅从window对象中获取您感兴趣的属性,即

protocol + '//' + hostname + pathname
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.