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

标签 javascript decodeuricomponent

我刚刚用 AJAX 测试了一些东西,我发现如果我发出警告就成功了

alert(decodeURI('%'));

alert(encodeURIComponent('%'));

浏览器出现以下代码错误。

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

如果我使用任何其他字符串,它就可以正常工作。
是我错过了什么吗?

最佳答案

最近,我的代码中的一个 decodeURIComponent 被 & 符号 % 绊倒了,谷歌搜索让我想到了这个问题。

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

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

  • 如果输入为空,则返回输入值不变
  • %25 替换每个 % 后面没有两位数(十六进制)的数字
  • 返回解码后的字符串

它也适用于这里的其他示例:

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

关于javascript - 为什么 decodeURIComponent ('%' ) 会锁定我的浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7449588/

相关文章:

javascript - 我不知道为什么这个 Canvas 是空的

javascript - $(this).attr ("href") 返回未定义

javascript - 我可以在脚本中完全禁用 'debugger' 吗?

javascript - 如何保存自动生成字段中的数据并将其与单个 ID 关联?

javascript - 来自 Mongo 集合的条目超过 24 小时

javascript - ng-include 没有获取带有 utf-8 字符的文件名

Javascript - 非结构化 URL 的 URL 解码

javascript - HTML 不显示已解码的 %3C?