22

我正在尝试从链接中删除 URI 编码,但 decodeURI 似乎没有完全正常工作。

我的示例链接是这样的:/linkout?remoteUrl=http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-heroic-armies-marching

运行 JavaScript 脚本后,它看起来像这样:

http%3a%2f%2fsandbox.yoyogames.com%2fgames%2f171985-h-a-m-heroic-armies-marching

如何摆脱 URI 中剩余的不正确代码?

我的解码代码:

var href = $(this).attr('href');            // get the href
var href = decodeURI(href.substring(19));   // remove the outgoing part and remove the escaping
$(this).attr('href', 'http://'+href)        // change link on page
4

3 回答 3

53

url 看起来被编码了两次,我还建议使用 decodeURIComponent

decodeURIComponent(decodeURIComponent("http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-heroic-armies-marching"))

结果:“http://sandbox.yoyogames.com/games/171985-ham-heroic-armies-marching”

但是您应该检查为什么要提前对 url 进行两次编码

于 2012-07-04T06:40:50.807 回答
1

我刚刚在 PUT 动词的 ASHX 处理程序中遇到了这种情况。ASP.NET 显然正在为我编码我的 XML,因此不需要我对HttpUtility.UrlEncode的服务器端调用。通过调用客户端 Javascript decodeURI两次来修复它——在奶牛已经离开并且我发送的 HTTP 违反协议后关闭谷仓门。

我会评论并加一个 Tobias Krogh 的答案,但我没有这样做的意义......</p>

但是,我仍然认为重要的是要注意这里讨论的失败不是 Javascript decodeURI 或其他任何东西——它是数据验证错误。

于 2014-06-13T16:54:34.097 回答
1

我的实现是一个递归函数:

export function tryDecodeURLComponent(str: string, maxInterations = 30, iterations = 0): string {
    if (iterations >= maxInterations) {
        return str;
    } else if (typeof str === 'string' && (str.indexOf('%3D') !== -1 || str.indexOf('%25') !== -1)) {
        return tryDecodeURLComponent(decodeURIComponent(str), maxInterations, iterations + 1)
    }

    return decodeURIComponent(str);
}
  • str: 编码字符串。
  • maxInterations:尝试解码的最大递归迭代次数str默认值30:) 。
  • iterations:标志计数器迭代。
于 2020-07-31T00:43:55.430 回答