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

标签 javascript

不知何故,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 中不起作用。

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

  • window.location.hash 应始终返回 urlencoded 字符串,但这是一个 bugFirefox

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/

相关文章:

javascript - 缩小浏览器时元素宽度不起作用?

Javascript 将 UTC 时间转换为本地时间

javascript - 如何调试嵌入在页面中间的混淆 javascript?

javascript - 如何在 Google 文档脚本中加粗一行?

javascript - 浏览器重启后sessionStorage不清除

javascript - 是否可以使用 Streams api 在 Javascript 中实现 websocket?

javascript - 为什么当我运行 For 循环时它不起作用?

javascript - 比较数组中的数组

javascript - Node.js 的领域驱动设计

javascript - AJAX:简单的帖子不起作用