简体   繁体   中英

Strip Base64-encoded URL parameters with Javascript

I'm decoding my URL parameters in .NET as explained in this article . In some cases I need to get the URL parameters in Javascript. But the problem is that some parameter values end at a '='.

Example: ?itemID=Jj1TI9KmB74=&cat=1

Javascript function:

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

I know my problem is at the split-function in the for-loop but I don't know how to solve it. I also used jsuri for this but the problem still exists. Can I solve this in Javascript or do I need to reconsider my encryption-method?

Having an unencoded = in the URL is invalid. To do this right, you would have to additionally apply encodeURIComponent() on the base64 encoded data.

Whether the base64 encoding still makes sense then, is for you to decide.

Reference: RFC 3986: Reserved characters

Having = unencoded in the URI query is invalid. You should escape it. However, for completeness, if you really needed to do this, try this:

Extra note: if you escaped the = using URI encoding, on the server side (eg $_GET) it'll be automatically decoded. With JavaScript and location , however, you must decode it first ( decodeURIComponent ) to work with it.

Instead of doing:

hash = hashes[i].split('=');

where subsequent equals signs are split too, do this instead (a non-greedy match before the first equals symbol for the key name, the rest for the value):

match = hashes[i].match(/([^=]+?)=(.+)/);
key = match[1];
value = match[2];

I assume you can't control the process generating the =s? As Pekka said it's wrong.

However you could manually break the string at the first =, eg

var i = hashes[i].indexof('=');
if (i > 0)
{
    var key = hashes[i].substring(0,i);
    vars.push(key);
    if ((i+1) < hashes[i].length)
    {
        vars[key] = hashes[i].substring(i+1);
    }
}
else
{
    // No value
    vars.push(hashes[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM