2

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?

2
  • So … basically … your query string is improperly formed. How about fixing whatever is generating it instead of trying to hack round the errors? Commented Aug 2, 2016 at 10:54
  • @Quentin This is how asp.net identity generates a code in order to reset a password, I didn't write it by my own and don't really want to try changing their system.. Commented Aug 2, 2016 at 11:09

1 Answer 1

1

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]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, that worked perfectly!! Just one thing, I got an error: 'query is not defined' so I replaced it with: var vars = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); is there any shorter way? Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.