Javascript 在window.location.hash中执行子字符串
在不同的浏览器中,window.location.hash的处理方式不同。如果我有一个网址如下Javascript 在window.location.hash中执行子字符串,javascript,Javascript,在不同的浏览器中,window.location.hash的处理方式不同。如果我有一个网址如下 http://maps-demo.bytecraft.com.my/postdemo/parcel #parcel/history/1?as=json&desc[]=ctime&desc[]=history_id 我对获取#parcel/history/and?as=json之间的值感兴趣。。。所以substring语句类似于 window.location.hash.sub
http://maps-demo.bytecraft.com.my/postdemo/parcel
#parcel/history/1?as=json&desc[]=ctime&desc[]=history_id
我对获取#parcel/history/and?as=json之间的值感兴趣。。。所以substring语句类似于
window.location.hash.substring(14, window.location.hash.search(/\?/g));
我在firefox 3.0.10中可以毫无问题地工作,但在Opera 9.60中,相同的子字符串语句不起作用
在快速搜索之后,我发现了一些可能有用的有趣信息
- window.location.hash应始终返回urlencoded字符串,但这是一个in
- Opera只返回#parcel/history/1并忽略剩余的字符串,这就是我的substring语句失败的主要原因
如果要提取#parcel/history/和?as=json…之间的字符串,有没有更好的方法。。。。除了正则表达式 这是我目前解决这个问题的方法
var get_hash_end = function(_hash) {
var result = _hash.length;
if(_hash.search(/\?/g) != -1) {
result = _hash.search(/\?/g);
}
return result;
};
您可以只使用
window.location.href
而不是hash,但为什么不使用regex呢?比基于字符N的子字符串的方法更可靠,未来更安全。请尝试:
window.location.href.match(/#parcel\/history\/(.*?)(\?|$)/)[1]
正则表达式并非总是正确的答案,但有时它只是正确的
编辑:清理方法封装
function GetValue()
{
var m = window.location.href.match(/#parcel\/history\/(.*?)(\?|$)/);
return m ? m[1] : null;
}
试试这个:
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
你也可以这样做:
var whatYouWant=window.location.hash.split(“?”)[0]。子字符串(14) 以前从未见过锚定标签被如此严重地滥用,哇,相当:)-值得一指out@Deviant嘿,您会惊讶地看到vmware server 2.0使用的哈希看起来像这样{e:%22HostSystem | ha主机%22,w:{t:true,i:0}