在window.location.hash中执行子字符串

问题描述:

不知何故,window.location.hash在不同浏览器中的处理方式不同。如果我有以下网址

Somehow window.location.hash is being handled differently in different browsers. If I have a url as follows

http://maps-demo.bytecraft.com.my/postdemo/parcel
    #parcel/history/1?as=json&desc[]=ctime&desc[]=history_id

我有兴趣在#parcel / history /和?as = json之间获取值...所以substring语句类似于

and I am interested in getting values in between #parcel/history/ and ?as=json ... so the substring statement would be something similar to

window.location.hash.substring(14, window.location.hash.search(/\?/g));

我在firefox 3.0.10中有这个工作没有问题但是相同的substring语句不起作用Opera 9.60。

I have that work in firefox 3.0.10 without problem but the same substring statement doesn't work in Opera 9.60.

经过一些快速搜索后,我发现了一些可能有用的有趣信息

After some quick searching, I found some interesting info that may help


  • window.location.hash应该始终返回urlencoded字符串,但这是 bug Firefox

  • window.location.hash should always return urlencoded string, but this is a bug in Firefox

如果URL的哈希部分包含编码字符(请参阅Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent),则哈希返回已解码的URL部分。这是Firefox中的一个错误。 href,search和pathname返回正确的编码URL部分。

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并忽略剩余的字符串,这是我的substring语句失败的主要原因...

  • 有没有更好的方法如果我想在#parcel / history /和?as = json ....之间提取字符串,除了正则表达式?!

    Is there a better way if I want to extract the string between #parcel/history/ and ?as=json.... besides regular expression?!

试试这个:

var match = window.location.href.match(/^[^#]+#([^?]*)\??(.*)/);
var hashPath = match[1];
var hashQuery = match[2];

这与哈希的以下部分相符:

This matches the following parts of the hash:

…#parcel/history/1?as=json&desc[]=ctime&desc[]=history_id
  \______________/ \____________________________________/
   hashPath         hashQuery