如果我使用:

alert(window.location.href);

我得到了包括查询字符串在内的所有信息。是否有一种方法只得到主url部分,例如:

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

而不是

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

当前回答

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

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

其他回答

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

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

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

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

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

只是使用URL的另一种选择

var theUrl = new URL(window.location.href);
theUrl.search = ""; //Remove any params
theUrl //as URL object
theUrl.href //as a string

如果你查看文档,你可以从窗口对象中获取你感兴趣的属性。

protocol + '//' + hostname + pathname