Javascript 没有完全工作

Javascript 没有完全工作,javascript,jquery,Javascript,Jquery,我试图从链接中删除URI编码,但decodeURI似乎没有完全工作 我的示例链接是:/linkout?remoteUrl=http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-herome-arms-marching 运行JavaScript脚本后,如下所示: http%3a%2f%2fsandbox.yoyogames.com%2fgames%2f171985-h-a-m-heroic-armies-marchi

我试图从链接中删除URI编码,但decodeURI似乎没有完全工作

我的示例链接是:
/linkout?remoteUrl=http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-herome-arms-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

url看起来是经过两次编码的,我还建议使用decodeURIComponent

decodeURIComponent(decodeURIComponent("http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-heroic-armies-marching"))
结果: "http://sandbox.yoyogames.com/games/171985-h-a-m-heroic-armies-marching"


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

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

我会对托拜厄斯·克罗的回答发表评论,再加上一句,但我没有理由这么做


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

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

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
    :编码字符串
  • maxInteractions
    :尝试解码的最大递归迭代次数
    str
    (默认值:
    30
  • 迭代
    :标记计数器迭代

使用decodeURIComponent()代替请注意,在一次执行过程中构造两次“$(this)”对象不是一个好主意,因此在函数开头缓存一次,并在需要时使用缓存的对象。
$(this).attr('href')
只是更长,写入
this.href
的速度较慢-在重新缩进时丢失。。。谢谢你的提示:)comment+1我写这段代码不是为了我的网站,而是为了一个用户脚本。我不知道他们为什么要对URI进行双重编码,我会在某个时候问他们。无论如何,执行decodeURIComponent两次应该可以解决您的问题:)