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?

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.