'Javascript check if url param exists

I'm running an A/B test to see if showing more items is better for conversion. But it seems that the code sometimes causes errors.. But I can't find any errors and don't know when they occur.

In my test I check whether the url param IC exists and if it doesn't exists I will add this.

This is my code:

function checkIfAlreadyPaginated()
  {
        var field = 'IC';
    var url = window.location.href;
    if(url.indexOf('?' + field + '=') != -1)
        return true;
    else if(url.indexOf('&' + field + '=') != -1)
        return true;
    return false;
  }
function insertParam(key, value) {
        key = encodeURIComponent (key); value = encodeURIComponent (value);

        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            return '?' + key + '=' + value;
        }
        else {

            var i = kvp.length; var x; while (i--) {
                x = kvp[i].split('=');

                if (x[0] == key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i < 0) { kvp[kvp.length] = [key, value].join('='); }

            return '?'+kvp.join('&');
        }
    }
var itemsPerPage = 48;
if(!checkIfAlreadyPaginated())
    {
      document.location.search = insertParam('IC', itemsPerPage);
    }

Does someone spot possible issues? I'm running the test via VWO.com.



Solution 1:[1]

If there is a Javascript error you should see it in the browser console and share it with us.

In any case, I would do it by creating a JS Object first. I find it easier to work with.

In the following code I added the option to do the checking for multiple params of the querystring. If you only need to check the IC you can simplify it a bit. I tested it on a blank test.html.

<script type="text/javascript">
// get the current params of the querystring
var querystringItems = document.location.search.substr(1).split('&');

// create an object
var querystringObject = {};
for(i=0;i<querystringItems.length;++i) {
    param = querystringItems[i].split('=');
    querystringObject[param[0]] = param[1];
}

// Define the keys to be searched for and their default value when they are not present
var requiredKeys = {"IC":48, "test": "me"};

// Do the checking on the querystringObject for each requiredKeys
var doreload = false;
for (var key in requiredKeys) {
    if (typeof querystringObject[key] == 'undefined') {
        doreload = true;
        // Create the missing parameter and assign the default value
        querystringObject[key] = requiredKeys[key];
    }
}

// If any of the requiredKeys was missing ...
if (doreload) {
    // rebuild the querystring
    var querystring = '?';
    for (var key in querystringObject) {
        querystring+=key+'='+querystringObject[key]+'&';
    }
    querystring=querystring.substr(0,querystring.length-1);
    // reload page
    document.location.search = querystring;
}

// assign the values to javascript variables (assuming you had it like this because you needed it)
var itemsPerPage = querystringObject.IC;
</script>

Solution 2:[2]

Here is an example to check this:

//get URL params into string:
paramStr = window.location.substring(window.location.indexOf('?'), window.location.length;
//turn string into array
paramArray = paramStr.split('&');
//prepare final array of params
params = {};
//prepare the index of IC parameter
icLoc = -1; //this is negative 1 so that you know if it was found or not
//for each item in array
for(var i in paramArray){
    //push its name and value to the final array
    params.push(paramArray[i].split('='));
    //if the parameter name is IC, output its location in array
    if(params[i][0] === 'IC'){
        icLoc = i;
    }
}

If IC is not found, icLoc will be -1.

If it is found, the value of IC in the URL parameters is params[icLoc][1]


Example result for query string ?foo=bar&code=cool&IC=HelloWorld:
params = {'foo': 'bar', 'code': 'cool', 'IC': 'HelloWorld'}
icLoc = 2


Example for query string ?foo=bar&code=cool:
params = {'foo': 'bar', 'code': 'cool'}
icLoc = -1

Solution 3:[3]

Here id is the param I'm using for a test. Pass the argument which you want to check whether it exists or not.

function queryParamExistUrl(param = '') {
            if (new URLSearchParams(window.location.search).get(param) != null)
                return true
            return false
        }
        console.log(queryParamExistUrl('id'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 MineAndCraft12
Solution 3 Bairavan