-2

I have a string of url encoded characters.

wondering if there is a javascript function that can replace all the url encoded characters with normal string characters.

i know i can use the replace function, but it only replaces one certain character an not all at once

for example, I am looking for one function that will replace all the url encoded characters in this string:

string urlEncoded = '1%20day%20%40work!%20Where%20are%20you%3F'

and give me this string:

string replaced = '1 day @ work! Where are you?'

thanks a lot

4 Answers4

0
string replaced = decodeURIComponent(urlEncoded);

There is also just decodeURI but this does not cope with "special" characters, such as & ? ! # etc

freefaller
  • 19,368
  • 7
  • 57
  • 87
0

Use decodeURIComponent(string) for that purpose.

string urlEncoded = '1%20day%20%40work!%20Where%20are%20you%3F';
string replaced = decodeURIComponent(urlEncoded);
alert(replaced);

More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURIComponent

Karl-Johan Sjögren
  • 16,544
  • 7
  • 59
  • 68
  • 2
    Please refrain from linking to w3school, see http://w3fools.com for why. The page you link to *might* have correct information, but the site is full of incorrect and misleading information, and linking to the site gives them credibility they do **not** deserve – freefaller Jul 21 '12 at 09:37
  • You are right @freefaller, I checked the information so that it was correct before posting but it was mainly laziness from my side that I took the first hit on Google. Updated to a link on Mozilla Developer Network instead that has the same info. – Karl-Johan Sjögren Jul 21 '12 at 09:40
  • 1
    If you have Google account then you should be able to block all results from them, problem solved! (**If** you have a Google account) – freefaller Jul 21 '12 at 09:42
  • Good idea, added it to my blocklist :) – Karl-Johan Sjögren Jul 21 '12 at 09:45
  • Yes if you encoded string have encoded spaces (%20) or newlines (%0D%0A) the will be properly decoded. – Karl-Johan Sjögren Jul 21 '12 at 10:16
0

Use decodeURIComponent(urlEncoded)

Dmitry Poroh
  • 3,705
  • 20
  • 34
-1

You are looking for unescape

var decoded = unescape(urlEncoded);
nico
  • 50,859
  • 17
  • 87
  • 112
  • escape()/unescape() shouldn't be used for URIs though, see http://stackoverflow.com/questions/75980/best-practice-escape-or-encodeuri-encodeuricomponent for more information about this. – Karl-Johan Sjögren Jul 21 '12 at 09:22
  • @Karl-JohanSjögren: Now, he is not mentioning URLs anywhere, is he? – nico Jul 21 '12 at 09:23
  • @Karl-JohanSjögren: *URL encoding* is the encoding technique, it does not in any way mean that he is encoding URLs. In fact it seems pretty clear from the example that he is encoding a generic string. – nico Jul 21 '12 at 09:48