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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6257463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:58:23  来源:igfitidea点击:

How to get the URL without any parameters in JavaScript?

javascript

提问by Tyler

If I use:

如果我使用:

alert(window.location.href);

I get everything including query strings. Is there a way to just get the main url part, for example:

我得到了包括查询字符串在内的所有内容。有没有办法只获取主 url 部分,例如:

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

instead of

代替

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

回答by lonesomeday

This is possible, but you'll have to build it manually from the locationobject:

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

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

回答by Oddman

Every answer is rather convoluted. Here:

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

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

Even if a ? isn't present, it'll still return the first argument, which will be your full URL, minus query string.

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

It's also protocol-agnostic, meaning you could even use it for things like ftp, itunes.etc.

它也是协议不可知的,这意味着你甚至可以将它用于诸如 ftp、itunes.etc 之类的东西。

回答by Niklas

Use indexOf

indexOf

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

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

回答by Headshota

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

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

回答by Mic

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

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

回答by AamirR

You can concat originand pathname, if theres present a port such as example.com:80, that will be included as well.

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

location.origin + location.pathname

回答by planetjones

If you look at the documentationyou can take just the properties you're interested in from the windowobject i.e.

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

protocol + '//' + hostname + pathname