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)
Odd*_*man 146
每个答案都相当复杂.这里:
var url = window.location.href.split('?')[0];
Run Code Online (Sandbox Code Playgroud)
即使是?如果不存在,它仍然会返回第一个参数,它将是您的完整URL,减去查询字符串.
它也是协议无关的,这意味着你甚至可以将它用于ftp,itunes.etc之类的东西.
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)
您可以连接origin和pathname,如果存在诸如 之类的端口example.com:80,则也将包含该端口。
location.origin + location.pathname
Run Code Online (Sandbox Code Playgroud)
var url = "tp://mysite.com/somedir/somefile/?foo=bar&loo=goo"
url.substring(0,url.indexOf("?"));
Run Code Online (Sandbox Code Playgroud)