在JavaScript或JQuery中替换解码url

Replace decode the url in JavaScript or JQuery

本文关键字:替换 解码 url JQuery JavaScript      更新时间:2023-09-26

如何在JavaScript或JQuery中解码url?


一个例子:我有这个url:

http://localhost:8080/map/file.html?var1=a%20b%20c&var2=d%20e%20f

如果我使用下面的代码,

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

我有这个:

http://localhost:8080/map/file.html?var1=ab%20c&var2=d%20e%20f

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

使用decodeURIComponent

var str = decodeURIComponent("This%20is%20a%20%string");

由于字符串是URL编码的,最后一次出现的%20在其后面包含一个额外的%,这可能是一个拼写错误

var str = decodeURIComponent("This%20is%20a%20string");
document.write(str);


编辑:

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

您只是在替换第一个元素。使用此RegEx与g替换所有:

var str = "This%20is%20a%20%string";
console.log(str.replace(/%20/g, " ");

EDIT:因为在您的编辑后,它出现了,您想使用@EasyBB

首次建议的decodeURIComponent()来取消对URI的捕获