51

I wrote a custom xml parser and its locking up on special characters. So naturally I urlencoded them into my database.

I can't seem to find an equivalent to php's urldecode().

Are there any extentions for jquery or javascript that can accomplish this?

Morten Siebuhr
  • 6,068
  • 4
  • 31
  • 43
Derek Adair
  • 21,846
  • 31
  • 97
  • 134

3 Answers3

106

You could use the decodeURIComponent function to convert the %xx into characters. However, to convert + into spaces you need to replace them in an extra step.

function urldecode(url) {
  return decodeURIComponent(url.replace(/\+/g, ' '));
}
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 3
    Excellent answer. I modified it slightly to take any variable: `function urldecode(str) { if (typeof str != "string") { return str; } return decodeURIComponent(str.replace(/\+/g, ' ')); }` –  Mar 12 '13 at 17:44
  • 2
    note this will not work for non-standard utf8 characters. E.g. `'%F7'`. php's urldecode will still store the correct bytes `0xF7` whereas `decodeURIComponent` will throw an error – JBaczuk Sep 10 '19 at 17:49
14

Check out this one

function urldecode (str) {
  return decodeURIComponent((str + '').replace(/\+/g, '%20'));
}
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Shahzeb chohan
  • 342
  • 3
  • 5
  • 2
    While a nice addition to the already suggested answers, you probably should include some suggestion of why it would be better / what the trade off is against the other options listed here. – EdC Sep 15 '12 at 01:31
  • From my understanding this will turn `+` into `%20`, which is the encoded value of a space (which then gets decoded by decodeURIComponent). So theoretically this will do the same as the accepted answer, just a different way of doing it. – Matt Sep 28 '13 at 19:13
-1

I think you need the decodeURI function.

Conner
  • 30,144
  • 8
  • 52
  • 73
shabunc
  • 23,119
  • 19
  • 77
  • 102