Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL-Parameter in Javascript doesn't work with urlencoded '&'

I wanna read an get-parameter from the URL in Javascript. I found this

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

The problem is, that my paramter is this:

iFZycPLh%Kf27ljF5Hkzp1cEAVR%oUL3$Mce&@XFcdHBb*CRyKkAufgVc32!hUni

I already made urlEncode, so its this:

iFZycPLh%25Kf27ljF5Hkzp1cEAVR%25oUL3%24Mce%26%40XFcdHBb*CRyKkAufgVc32!hUni

But still, if I call the getUrlParameter() function, I just get this as result:

iFZycPLh%Kf27ljF5Hkzp1cEAVR%oUL3$Mce

Does anyone know how I can fix that?

like image 868
progNewbie Avatar asked May 24 '26 01:05

progNewbie


1 Answers

You need to call decodeURIComponent on sParameterName[0] and sParameterName[1] instead of on the whole of search.substring(1)).

(i.e. on the components of it)

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        var key = decodeURIComponent(sParameterName[0]);
        var value = decodeURIComponent(sParameterName[1]);

        if (key === sParam) {
            return value === undefined ? true : value;
        }
    }
};

This is mentioned in zakinster's comment on the answer you link to.

like image 63
Quentin Avatar answered May 26 '26 13:05

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!