不知何故,window.location.hash 在不同浏览器中的处理方式有所不同。如果我有一个如下的网址
http://maps-demo.bytecraft.com.my/postdemo/parcel
#parcel/history/1?as=json&desc[]=ctime&desc[]=history_id
我有兴趣获取 #parcel/history/和 ?as=json 之间的值...因此子字符串语句类似于
window.location.hash.substring(14, window.location.hash.search(/\?/g));
我在 Firefox 3.0.10 中可以正常工作,但相同的子字符串语句在 Opera 9.60 中不起作用。
经过一些快速搜索,我发现了一些可能有帮助的有趣信息
If the hash part of the URL contains encoded characters (see Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent), hash returns the decoded URL part. This is a bug in Firefox. href, search and pathname return the correct, encoded URL parts.
- Opera 仅返回 #parcel/history/1 并忽略剩余的字符串,这就是我的子字符串语句失败的主要原因...
如果我想提取 #parcel/history/和 ?as=json...之间的字符串,除了正则表达式之外,还有更好的方法吗?!
最佳答案
试试这个:
var match = window.location.href.match(/^[^#]+#([^?]*)\??(.*)/);
var hashPath = match[1];
var hashQuery = match[2];
这与哈希的以下部分匹配:
…#parcel/history/1?as=json&desc[]=ctime&desc[]=history_id
\______________/ \____________________________________/
hashPath hashQuery
关于javascript - 在 window.location.hash 中执行子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/824040/