为什么decodeURIComponent('%')会锁定我的浏览器?

Cri*_*tiC 10 javascript decodeuricomponent

我只是用AJAX测试一些东西,如果我发出警报,我发现成功了

alert(decodeURI('%'));
Run Code Online (Sandbox Code Playgroud)

要么

alert(encodeURIComponent('%'));
Run Code Online (Sandbox Code Playgroud)

浏览器错误输出以下代码.

$.ajax({
   type: "POST",
   url: "some.php",
   data: "",
   success: function(html){
         alert(decodeURIComponent('%'));
//           alert(decodeURI('%'));
   }
 });
Run Code Online (Sandbox Code Playgroud)

如果我使用任何其他字符串,它的工作正常.
这是我错过的东西吗?

Hei*_*cht 20

最近decodeURIComponent,我的代码中的a 被与号绊倒了%,谷歌搜索使我想到了这个问题。

这是我用来处理%比 Ilia 版本短的函数:

function decodeURIComponentSafe(s) {
    if (!s) {
        return s;
    }
    return decodeURIComponent(s.replace(/%(?![0-9][0-9a-fA-F]+)/g, '%25'));
}
Run Code Online (Sandbox Code Playgroud)

  • 如果输入为空,则返回未更改的输入值
  • %两位数(十六进制)数字替换每个NOT 后跟%25
  • 返回解码后的字符串

它还适用于此处的其他示例:

  • decodeURIComponentSafe("%%20Visitors") // % Visitors
  • decodeURIComponentSafe("%Directory%20Name%") // %Directory Name%
  • decodeURIComponentSafe("%") // %
  • decodeURIComponentSafe("%1") // %1
  • decodeURIComponentSafe("%3F") // ?

  • 是的,这没有考虑 unicode:`encodeURIComponent("Ju")` 最终为 "%E5%84%92",这将无法在此函数中解码。正则表达式 `/%(?![0-9a-fA-F]+)/g` 更好。 (4认同)
  • decodeURIComponentSafe('%3f')。预期结果:?。实际结果:%25ef (3认同)

Jua*_*des 15

从控制台尝试时,Chrome barf.它给出了一个URIError:URI格式错误.%是一个转义字符,它不能单独使用.

  • 维基百科怎么样?http://en.wikipedia.org/wiki/Percent_encoding**字符百分比的百分比编码**由于百分比("%")字符用作百分比编码八位字节的指示符,因此必须将百分比编码为" %25"表示该八位字节用作URI中的数据. (3认同)

Ili*_*sev 6

关键在于,如果你使用单一,%它会破坏decodeURIComponent()函数的逻辑,因为它需要紧随其后的两位数据值,例如%20(空格).

周围有一个黑客.我们需要首先检查decodeURIComponent()实际上是否可以在给定的字符串上运行,如果不能按原样返回字符串.

例:

function decodeURIComponentSafe(uri, mod) {
    var out = new String(),
        arr,
        i = 0,
        l,
        x;
    typeof mod === "undefined" ? mod = 0 : 0;
    arr = uri.split(/(%(?:d0|d1)%.{2})/);
    for (l = arr.length; i < l; i++) {
        try {
            x = decodeURIComponent(arr[i]);
        } catch (e) {
            x = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i];
        }
        out += x;
    }
    return out;
}
Run Code Online (Sandbox Code Playgroud)

运行:

decodeURIComponent("%Directory%20Name%")
Run Code Online (Sandbox Code Playgroud)

会导致Uncaught URIError: URI malformed错误

而:

decodeURIComponentSafe("%Directory%20Name%") // %Directory%20Name%
Run Code Online (Sandbox Code Playgroud)

将返回初始字符串.

如果您希望拥有固定/正确的URI并且已经%转换为%25必须将其1作为附加参数传递给自定义函数:

decodeURIComponentSafe("%Directory%20Name%", 1) // "%25Directory%20Name%25"
Run Code Online (Sandbox Code Playgroud)