Reputation: 14320
How can I decode a url in JavaScript or JQuery?
An example: I've got this url:
http://localhost:8080/map/file.html?var1=a%20b%20c&var2=d%20e%20f
If I use code below,
var str = "var1=a%20b%20c&var2=d%20e%20f";
document.write(str.replace("%20", " "));
I've got this:
http://localhost:8080/map/file.html?var1=a b%20c&var2=d%20e%20f
What is the fast en the best way to decode the url?
Upvotes: 0
Views: 241
Reputation: 13211
You are only replacing the first element. Use this RegEx with g to replace all:
var str = "This%20is%20a%20%string";
console.log(str.replace(/%20/g, " ");
EDIT: as after your edit it appears, you want to unescape an URI use decodeURIComponent()
as first suggested by @EasyBB
Upvotes: 3
Reputation: 87233
var str = decodeURIComponent("This%20is%20a%20%string");
As the string is URL-encoded, the last occurrence of %20
contains an extra %
after it, which is probably a typo.
var str = decodeURIComponent("This%20is%20a%20string");
document.write(str);
EDIT:
var url = "http://localhost:8080/map/file.html?var1=a%20b%20c&var2=d%20e%20f";
document.write(decodeURIComponent(url));
Upvotes: 8