Question

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

Was it helpful?

Solution

OTHER TIPS

Here is a complete function (taken from PHPJS):

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
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]

Use this

unescape(str);

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

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

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.

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

var uri = "my test.asp?name=ståle&car=saab";
console.log(encodeURI(uri));

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top