user3378165 user3378165 - 4 months ago 23
Javascript Question

Get query string parameters including all characters with javascript

I need to get query string prameters by their names.

My parameters includes all kind of characters including '=' signs.

Here is an example:


http://MyProject/ResetPassword?userid=12489e2ss125-f031-4ef7d-95c9-80e894efc6a0&code=Ippr7HP/Fad2q3kKMehQtVYnbFcZp+h4ECS+RCQmN+KrcAM8N4tdeNciNEXlwkhnjF3tZgez1/a1Ca1018uXpodGEnPcyTjsfuSmyuS1hoRXY04wKLgiyW031aLAYmua8yXLDdghgjo+0s7SUD7LWFMapMP8b3eN//ycbe1QNm6RVc7ahMs77ng6i6p6MScBefU/Rnj5ME7ly7tqw==


I tried that:

function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}


But it replaces the '+' signs with white spaces:


"Code":"Ippr7HP/Fad2q3kKMehQtVYnbFcZp h4ECS RCQmN KrcAM8N4tdeNciNEXlwkhnjF3tZgez1/a1Ca1018uXpodGEnPcyTJzsupjsfuSmyuS1hoRXY04wKLgiyW031aLAYmua8yXLDdghgjo 0s7SUD7LWFMapMP8b3eN//ycbe1QNm6RVc7ahMs77ng6i6p6MScBefU/Rnj5ME7ly7tqw==


I tried that:

function getParameterByName(key) {
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[key];
}


But that doesn't include '=' signs...

Any advise?

Answer

Your second attempt is close enough, you just need to join back value parts after .split('=')

function getParameterByName(parameterName) {
    var query = window.location.search.substring(1);
    var queryParameters = {};
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var keyValue = vars[i].split('=');
        var key = keyValue[0];
        var value = keyValue.slice(1).join('=');
        queryParameters[decodeURIComponent(key)] = decodeURIComponent(value);
    }

    return queryParameters[parameterName]
}