如何在JavaScript中获得没有任何参数的URL ?

如果我使用:

alert(window.location.href);

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

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

而不是

http://mysite.com/somedir/somefile/?foo=bar&loo=goo
215979 次浏览

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

location.protocol + '//' + location.host + location.pathname
var url = "tp://mysite.com/somedir/somefile/?foo=bar&loo=goo"


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

使用indexOf

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


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

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

protocol + '//' + hostname + pathname

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

每个答案都相当令人费解。在这里:

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

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

它也是协议无关的,这意味着你甚至可以用它来做ftp、itunes等事情。

你可以连接originpathname,如果有一个端口,如example.com:80,这也将包括在内。

location.origin + location.pathname

只是使用URL的另一种选择

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

我迟到了,但我最近不得不解决这个问题,我想我应该分享财富。

const url = window.location.origin + window.location.pathname
//http://example.com/somedir/somefile/

window.location.origin将给你基本url,在我们的测试用例中:http://example.com

window.location.pathname将给你路由路径(在基本url之后),在我们的测试用例/somedir/somefile

解决方案2

您可以简单地执行以下操作来删除查询参数。

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

使用URL()构造函数,然后提取并连接原点和路径名。这将自动从url中剥离搜索(又名查询)参数,只留下方案、域、端口和路径名。

const url = new URL('http://localhost:8080/index.html?search=foo&other=bar');
console.log(url.origin + url.pathname);

需要注意的是,这种类型的转换通常被称为归一化,特别是在这种情况下URI正常化。在您的环境中,可能已经存在具有更多选项的更健壮的库。