如何使用位置对象来解析URL而无需在javascript中重定向页面? [英] How to use location object to parse URL without redirecting the page in javascript?

查看:63
本文介绍了如何使用位置对象来解析URL而无需在javascript中重定向页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览器有一个非常有效的URL解析器,可以让你获得 location.href hash ,<$ c来自当前网址的$ c>查询等。我想使用它而不是使用正则表达式编写代码。

The browser has a very efficient URL parser that let you get location.href, hash, query, etc from the current URL. I'd like to use it instead of coding something using regexes.

如果你设置 location.href 或者做 location.replace(url),该页面会在Chrome中重定向。我试图在这个浏览器中获取位置原型,但我找不到 location.prototype 。有一个位置.__ proto __ 在js控制台中被描述为 Location 类,但我找不到一种实例化它的方法。另外,我需要一个跨浏览器解决方案并且IE中没有 __ proto __

If you set location.href or do location.replace(url), the page gets redirected in Chrome. I tried to get the prototype of location in this browser, but I can't find location.prototype. There is a location.__proto__ which is described as the Location class in the js console, but I can't find a way to instantiate it. Plus, I need a cross browser solution and __proto__ is not available in IE.

如果不可能,请不要不给我一个正则表达式替代方案,只要告诉我一个事实,只要你能用证据支持它。

If it's not possible, don't give me a regex alternative, just tell me the hard truth, provided you can back it up with evidences.

推荐答案

是,这是非常可能的!如果您创建一个新的 a 对象,则可以使用位置字段而无需重定向浏览器。

Yes, it's very much possible! If you create a new a object, you can use the location fields without redirecting the browser.

例如:

var a = document.createElement('a');
a.href = "http://openid.neosmart.net/mqudsi#fake"

您现在可以访问 .hash .pathname .host ,以及所有其他位置的好东西!

You can now access .hash, .pathname, .host, and all the other location goodies!

> console.log(a.host);
openid.neosmart.net

这篇关于如何使用位置对象来解析URL而无需在javascript中重定向页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆