18

I would like to know what this code does? I am using it almost all the time but I don't know what it does.

function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
    var singleParam = params[i].split("=");
    if (singleParam[0] == paramToRetrieve)
        return singleParam[1];
}
28

It extracts one named parameter from the QueryString (URL)

http://domainname.com/page.aspx?parameter1=xxx&parameter2=yyy

var value=getQueryStringParameter('parameter1');

It is used in many examples and most of the time not necessary (and bloats your code)
because SharePoint has multiple implementations in core libraries

Usage depends on whether you want to check for non-existing values or CaSe matching

(init.js) GetUrlKeyValue

var value=GetUrlKeyValue( 'parameter1' );

returns an empty string "" if the parameter does not exist

GetUrlKeyValue( parameter , [maintain encoded value] , [url] , [ignorecase] )

[encoded] - Boolean, false(default) decodes value with decodeURIComponent() true: maintains the original string

[url] - String use another string, default: window.location.href (current URL)

[ignorecase] - Boolean when true ignores case

(init.js) JSRequest

JSRequest.EnsureSetup();
var value=JSRequest.QueryString['parameter1'];

returns undefined if the parameter does not exist

You have to do the JSRequest.EnsureSetup() `yourself as SharePoint does not seem to use its own code on each and every page.

JSRequest at least builts a QueryString object, so you only have to EnsureSetup() once (per page).
The getQueryStringParameter and GetUrlKeyValue functions execute the same code over and over for each and every call.

Even Microsoft duplicates functionality:

(SP.init.js) SP.ScriptHelpers.getUrlQueryPairs

Even more SharePoint code that does the same

 var QS = SP.ScriptHelpers.getUrlQueryPairs(document.location.href)
 var value=QS['parameter1'];

Note: QS['parameter'] is the same as QS.parameter


J1 J5 iJS iDOC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.