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

Tyl*_*ler 151 javascript

如果我使用:

alert(window.location.href);
Run Code Online (Sandbox Code Playgroud)

我得到的一切包括查询字符串.有没有办法获得主网址部分,例如:

http://mysite.com/somedir/somefile/
Run Code Online (Sandbox Code Playgroud)

代替

http://mysite.com/somedir/somefile/?foo=bar&loo=goo
Run Code Online (Sandbox Code Playgroud)

lon*_*day 254

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

location.protocol + '//' + location.host + location.pathname
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您不需要提供location.protocol,因为所有现代浏览器(包括IE6)都将自动继承当前协议.即:`'//'+ location.host + location.pathname` (13认同)
  • @JonnyReeves如果您在当前文档中使用它,那是真的:好点.有时可能需要,例如,如果将URL作为纯文本输出. (10认同)
  • 它缺少端口,因此这将为页面`http://www.example.com:8080 / asdf.html?foo = bar`返回错误的结果 (3认同)
  • 您可以使用“ location.origin”保存一些字符,我相信这也可以解决@izogfif的问题。 (2认同)

Odd*_*man 146

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

var url = window.location.href.split('?')[0];
Run Code Online (Sandbox Code Playgroud)

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

它也是协议无关的,这意味着你甚至可以将它用于ftp,itunes.etc之类的东西.

  • 如果你需要删除锚点`window.location.href.split(/ [?#] /)[0];` (34认同)

Nik*_*las 14

使用 indexOf

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

if (url.indexOf("?")>-1){
url = url.substr(0,url.indexOf("?"));
}
Run Code Online (Sandbox Code Playgroud)


zr0*_*ty7 13

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

const url = new URL('http://example.com/somedir/?foo=bar');
console.log(url.origin + url.pathname);
Run Code Online (Sandbox Code Playgroud)

请注意,这种类型的转换通常称为规范化,特别是在本例中URI 规范化。可能已经存在一些库可以在您的环境中提供更多选项,从而更稳健地实现此目的。


Rob*_*ick 12

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

const url = window.location.origin + window.location.pathname
//http://example.com/somedir/somefile/
Run Code Online (Sandbox Code Playgroud)

window.location.origin 在我们的测试用例中,将为您提供基本网址: http://example.com

window.location.pathname 在我们的测试用例中,将为您提供路由路径(在基本 url 之后) /somedir/somefile

解决方案 2

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

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


dig*_*tie 10

使用 URL 是另一种选择

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


Aam*_*irR 6

您可以连接originpathname,如果存在诸如 之类的端口example.com:80,则也将包含该端口。

location.origin + location.pathname
Run Code Online (Sandbox Code Playgroud)


Hea*_*ota 5

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

url.substring(0,url.indexOf("?"));
Run Code Online (Sandbox Code Playgroud)

  • 这假定,该参数是定义的.更好的是`url.split('?')[0]` (3认同)

Mic*_*Mic 5

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