如何解码JavaScript中的字符串?

TK1*_*123 7 javascript

这对我不起作用:

var foo = "Collection%3A 9 Bad Interviews With Former GOP Presidential Candidates";

console.log(decodeURI(foo));
Run Code Online (Sandbox Code Playgroud)

它输出:

Collection%3A 9 Bad Interviews With Former GOP Presidential Candidates
Run Code Online (Sandbox Code Playgroud)

这是不正确的,如果你在这样的网站上输入foo字符串:

http://meyerweb.com/eric/tools/dencoder/

它显示正确的输出,即:

Collection: 9 Bad Interviews With Former GOP Presidential Candidates
Run Code Online (Sandbox Code Playgroud)

如何正确解码字符串?

vir*_*has 10

decodeURIdecodeURIComponent之间的差异

主要区别是:

  • encodeURI旨在用于完整URI.
  • encodeURIComponent旨在用于.. well .. URI组件,它是位于分隔符之间的任何部分(; /?:@&= + $,#).

    因此,在encodeURIComponent中,这些分隔符也被编码,因为它们被视为文本而不是特殊字符.

    现在回到解码函数之间的差异,每个函数解码由其相应的编码对应物生成的字符串,处理特殊字符的语义及其处理.

    所以在你的情况下,decodeURIComponent完成这项工作


    Joe*_*Joe 6

    使用decodeURIComponent

    var decoded = decodeURIComponent(foo);
    
    Run Code Online (Sandbox Code Playgroud)

    decodeURI如您所见,有一些问题。decodeURIComponent是这项工作的最佳实践工具。