window.location.hash的编码

Mic*_*ael 41 html javascript url encoding fragment-identifier

是否window.location.hash包含url部分的编码或解码表示?

当我打开相同的URL(http://localhost/something/#%C3%BC其中,%C3%BC转化为ü在Firefox 3.5和Internet Explorer 8),我得到不同的值document.location.hash:

  • IE8: #%C3%BC
  • FF3.5:

有没有办法在两个浏览器中获得一个变体?

Eli*_*rey 38

不幸的是,这是Firefox中的一个错误,因为它location.hash在访问时会解码额外的时间.例如,在Firefox中试试这个:

location.hash = "#%30";
location.hash === "#0"; // This is wrong, it should be "#%30"
Run Code Online (Sandbox Code Playgroud)

唯一的跨浏览器解决方案是使用(location.href.split("#")[1] || "")而不是获取哈希.设置哈希使用location.hash似乎适用于所有支持的浏览器location.hash.

  • @Christophe:哈希本身中可能的'#'应编码为'%23'.更确切地说,你显然可以使用`location.href.split('#').splice(1).join('#')`.在这种情况下甚至不需要添加`|| ""因为如果首先没有哈希,结果是一个空字符串. (5认同)

Mic*_*ael 6

回答我自己的问题,我目前的解决方案是解析window.location.href而不是使用window.location.hash,因为前者总是(即在每个浏览器中)url编码.因此,CMS提出的decodeURIComponent功能始终可以安全使用.YUI做同样的事,因此它不会那么错......


CMS*_*CMS 5

您可以使用decodeURIComponent,它会在所有情况下返回:

decodeURIComponent('#%C3%BC'); // #ü
decodeURIComponent('#ü'); // #ü
Run Code Online (Sandbox Code Playgroud)

在这里尝试一下

  • 假设我想将哈希用于搜索功能,并且有人想搜索“%40”(但不是“@”)。根据他的浏览器,我会得到 `#%2540` (IE) 或 `#%40` (FF) 作为 `location.hash`。如果我解码它,我会在不同的浏览器中得到不同的结果。 (6认同)
  • 不是解决方案,因为:`decodeURIComponent('%2540'); // %40 (IE)` 但 `decodeURIComponent('%40'); //@(FF)` (3认同)