在 javascript 中创建一个新的 Location 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3213531/
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
Creating a new Location object in javascript
提问by Josh Johnson
Is it possible to create a new Location object in javascript? I have a url as a string and I would like to leverage what javascript already provides to gain access to the different parts of it.
是否可以在 javascript 中创建一个新的 Location 对象?我有一个 url 作为字符串,我想利用 javascript 已经提供的内容来访问它的不同部分。
Here's an example of what I'm talking about (I know this doesn't work):
这是我正在谈论的一个例子(我知道这行不通):
var url = new window.location("http://www.example.com/some/path?name=value#anchor");
var protocol = url.protocol;
var hash = url.hash;
// etc etc
Is anything like this possible or would I essentially have to create this object myself?
这样的事情是可能的还是我基本上必须自己创建这个对象?
回答by CMS
Well, you could use an anchor element to extract the url parts, for example:
好吧,您可以使用锚元素来提取 url 部分,例如:
var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
var protocol = url.protocol;
var hash = url.hash;
alert('protocol: ' + protocol);
alert('hash: ' + hash);
?
It works on all modern browsers and even on IE 5.5+.
它适用于所有现代浏览器,甚至适用于 IE 5.5+。
Check an example here.
在此处查看示例。
回答by Rael Gugelmin Cunha
How about use the standard URL object?
如何使用标准的URL 对象?
var url = new URL("http://www.example.com/some/path?name=value#anchor");
var protocol = url.protocol;
var hash = url.hash;
Warning: This interface is a bit new, so, if you're not using a transpiler, please, check the compatibility tableand do your tests at target browsers.
回答by epascarello
You can leverage the power of an anchor element
您可以利用锚元素的力量
var aLink = document.createElement("a");
aLink.href="http://www.example.com/foo/bar.html?q=123#asdf";
alert(aLink.pathname);
回答by Andir
You can parse it in a regex to get the parts as matches... I don't have the full code right now, but this can be used to get the querydata:
您可以在正则表达式中解析它以获得匹配的部分......我现在没有完整的代码,但这可用于获取查询数据:
var myUrl = window.location.href;
var matches = myUrl.match(/([^\?]+)\?(.+)/);
var queryData = matches[2];
matches[0] is the full string, matches(1) is the first part of the URL (up to the ?)... you could build up a regular expression to parse each part of a string url if you want...
match[0] 是完整的字符串,matches(1) 是 URL 的第一部分(直到 ?)...如果需要,您可以构建一个正则表达式来解析字符串 url 的每个部分...
You can also use one of the many libraries already out there for this.
为此,您还可以使用现有的众多库之一。

