0

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?

5
  • 1
    Possible duplicate of Replacing all occurrences of a string in JavaScript Commented Nov 24, 2015 at 13:53
  • 2
    @Juhana While that does do what the OP is asking, I think Tushar's answer is probably what the OP actually needs Commented Nov 24, 2015 at 13:54
  • 1
    Yeah, although the actual problem has more than its share of duplicates too... Commented Nov 24, 2015 at 13:55
  • 1
    Tushars answer is the correct one, since it is a URL and you are trying to decode the encoded URI Commented Nov 24, 2015 at 14:03
  • @Juhana: I've edit my question, it was not so clear that is was an url Commented Nov 24, 2015 at 14:04

2 Answers 2

8

Use decodeURIComponent

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));

Sign up to request clarification or add additional context in comments.

11 Comments

This will fail due to %20%
@AlexK. I guess that is copy-paste error as the string is clearly encoded string.
Well that's not an actual URI Component then.
@CodeiSir That's because this is probably an XY Problem, and Tushar's answer deals with the actual underlying issue, not the immediate need.
I expected this as well, that why I gave you an upvote ;)
|
3

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

1 Comment

as for this answer g is a global modifier of the RegExp expressions. Just like there is m == multiline, i == case insensitive...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.