替换解码JavaScript或JQuery中的url

H. *_*lyn 0 javascript string jquery replace

如何解码JavaScript或JQuery中的URL?


一个例子:我有这个网址:

HTTP://本地主机:8080 /图/ file.html VAR1 =一%20B%20C&VAR2 = d%20E%20F

如果我使用下面的代码,

var str = "var1=a%20b%20c&var2=d%20e%20f";
document.write(str.replace("%20", " "));
Run Code Online (Sandbox Code Playgroud)

我有这个:

HTTP://本地主机:8080 /图/ file.html VAR1 = AB%20c的&VAR2 = d%20E%20F

什么是快速解码网址的最佳方法?

Tus*_*har 8

使用 decodeURIComponent

var str = decodeURIComponent("This%20is%20a%20%string");
Run Code Online (Sandbox Code Playgroud)

由于字符串是URL编码的,最后一次出现后会%20包含一个额外的%,这可能是一个错字.

var str = decodeURIComponent("This%20is%20a%20string");
document.write(str);
Run Code Online (Sandbox Code Playgroud)


编辑:

var url = "http://localhost:8080/map/file.html?var1=a%20b%20c&var2=d%20e%20f";
document.write(decodeURIComponent(url));
Run Code Online (Sandbox Code Playgroud)

  • @CodeiSir那是因为这可能是[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem),而Tushar的回答涉及实际的潜在问题,而不是迫切需要. (3认同)