157

What's the best JavaScript URL decode utility? Encoding would be nice too and working well with jQuery is an added bonus.

at.
  • 50,922
  • 104
  • 292
  • 461

9 Answers9

239

Here is a complete function (taken from PHPJS):

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
Matt
  • 74,352
  • 26
  • 153
  • 180
anshuman
  • 3,496
  • 1
  • 19
  • 13
  • 34
    +1: this is the true urldecode, handles the case of space being encoded as +, thanks a lot – Máthé Endre-Botond Oct 30 '11 at 14:13
  • 1
    This is what I needed to use when the data was encoded with PHP's urlencode() function. – Scott Keck-Warren Feb 20 '12 at 16:22
  • 1
    If I'm not mistaken, this is decoding + as %20, not as space - that's not really what you wanted here, is it? You'd want the space, not another version of an encoded character... no? – Chris Moschini Mar 01 '13 at 09:09
  • 8
    @ChrisMoschini: No, this is correct because the replace occurs before the decode call. – lfaraone Mar 27 '13 at 18:45
  • @lfaraone I see - so the goal of that tidbit of code is to ensure plus signs come out as spaces in the output instead of being left be as plusses by decodeURIComponent. – Chris Moschini Mar 27 '13 at 18:54
  • 1
    Thank you so much!! This is a perfect way to handle strings in jquery which have been previously urlencoded with php, just what I needed!! – Dante Cullari May 03 '13 at 20:32
  • This method is also better if the string was encoded with `HttpServerUtility.UrlEncode` (which encodes spaces as "+"s) instead of `HttpServerUtility.UrlPathEncode` (which encodes spaces as "%20") in C#.NET, as well. – VoidKing Dec 11 '13 at 22:03
  • if, in PHP, you json_encode() a value and then put that in a cookie with setcookie(), you may need to do this before you JSON.parse() it. even though you didnt explicitly urlencode() it. – Octopus Sep 09 '14 at 22:17
  • Are the plus signes the only thing that needs to be replaced ? – mjs Mar 25 '15 at 22:14
  • @momo Other things taken care by decodeURIComponent. – anshuman Aug 18 '15 at 11:40
  • @anshuman What if I need to decode what I encoded using `urldecode`? Will `encodeURIComponent` work just fine or will I need to alter the input as you did with `urldecode`? – TheRealFakeNews Dec 02 '16 at 04:38
220

I've used encodeURIComponent() and decodeURIComponent() too.

TJL
  • 6,330
  • 8
  • 34
  • 36
Geoff
  • 9,470
  • 13
  • 52
  • 67
9

Use this

unescape(str);

I'm not a great JS programmer, tried all, and this worked awesome!

nithinreddy
  • 6,167
  • 4
  • 38
  • 44
  • 2
    Cool answer, but looks like it's [obsoleted](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FFunctions#escape_and_unescape_functions(Obsoleted_above_JavaScript_1.5)) in favor of `decodeURIComponent()` due to poor support of non-ASCII characters. – Brad Koch Jun 06 '13 at 14:35
9
decodeURIComponent(mystring);

you can get passed parameters by using this bit of code:

//parse URL to get values: var i = getUrlVars()["i"];
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Or this one-liner to get the parameters:

location.search.split("your_parameter=")[1]
Etienne Dupuis
  • 13,548
  • 6
  • 47
  • 58
3
//How decodeURIComponent Works

function proURIDecoder(val)
{
  val=val.replace(/\+/g, '%20');
  var str=val.split("%");
  var cval=str[0];
  for (var i=1;i<str.length;i++)
  {
    cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
  }

  return cval;
}

document.write(proURIDecoder(window.location.href));
Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
Irfan M
  • 51
  • 2
2

If you are responsible for encoding the data in PHP using urlencode, PHP's rawurlencode works with JavaScript's decodeURIComponent without needing to replace the + character.

Brent Self
  • 373
  • 2
  • 5
0

Here's what I used:

In JavaScript:

var url = "http://www.mynewsfeed.com/articles/index.php?id=17";
var encoded_url = encodeURIComponent(url);

var decoded_url = decodeURIComponent(encoded_url);

In PHP:

$url = "http://www.mynewsfeed.com/articles/index.php?id=17";
$encoded_url = url_encode(url);

$decoded_url = url_decode($encoded_url);

You can also try it online here: http://www.mynewsfeed.x10.mx/articles/index.php?id=17

0

var uri = "my test.asp?name=ståle&car=saab";
console.log(encodeURI(uri));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

decodeURIComponent() is fine, but you never want ot use encodeURIComponent() directly. This fails to escape reserved characters like *, !, ', (, and ). Check out RFC3986, where this is defined, for more info on that. The Mozilla Developer Network documentation gives both a good explanation and a solution. Explanation...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

Solution...

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

In case you're not sure, check out a good, working demo at JSBin.com. Compare this with a bad, working demo at JSBin.com using encodeURIComponent() directly.

Good code results:

thing%2athing%20thing%21

Bad code results from encodeURIComponent():

thing*thing%20thing!

Community
  • 1
  • 1
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133