在 JavaScript 中创建一个新的 Location 对象
是否可以在 JavaScript 中创建一个新的 Location 对象?我有一个字符串形式的 url,我想利用 javascript 已经提供的内容来访问它的不同部分。
这是我正在谈论的一个示例(我知道这不起作用):
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 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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,您可以使用锚元素来提取 url 部分,例如:
它适用于所有现代浏览器,甚至 IE 5.5+。
请查看此处的示例。
Well, you could use an anchor element to extract the url parts, for example:
It works on all modern browsers and even on IE 5.5+.
Check an example here.
使用标准 URL 对象怎么样?
然后
console.log(hash)
将输出#anchor
。警告:此界面有点新,因此,如果您不使用转译器,请检查兼容性表 并在目标浏览器上进行测试。
How about use the standard URL object?
Then
console.log(hash)
will output#anchor
.Warning: This interface is a bit new, so, if you're not using a transpiler, please, check the compatibility table and do your tests at target browsers.
您可以利用锚元素的力量
You can leverage the power of an anchor element
您可以在正则表达式中解析它以获取匹配的部分...我现在没有完整的代码,但这可以用于获取查询数据:
matches[0] 是完整的字符串, matches(1)是 URL 的第一部分(直到?)...如果需要,您可以构建一个正则表达式来解析字符串 url 的每个部分...
您还可以使用现有的许多库之一这。
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:
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...
You can also use one of the many libraries already out there for this.