Skip to Content

removeQueryParameter()

Remove a query parameter from a string.

JavaScript July 2, 2019

Usage

JavaScript
nebuala.removeQueryParameter(key, sourceURL)

Parameters

keys
(Required) (String/Array) The key(s) to remove
Default: None

sourceURL
(Required) (String) The URL (including query strings)
Default: None

Parameter Notes

keys can be a string or an array of strings to remove more than 1 query parameter.

Request or provide clarification »

Examples

Update the URL with the History API

JavaScript
if ( window.history.replaceState ){ //IE10+
    window.history.replaceState({}, document.title, nebula.removeQueryParameter('example', window.location.href));
}

Remove UTM parameters (multiple keys)

JavaScript
if ( window.history.replaceState ){ //IE10+
    window.history.replaceState({}, document.title, nebula.removeQueryParameter(['utm_campaign', 'utm_medium', 'utm_source', 'utm_content', 'utm_term'], window.location.href));
}

Additional Notes

Note that this does not change the active URL. It only returns the URL without the query string.

Source File

Located in /assets/js/nebula.js on line 3840.

JavaScript
nebula.removeQueryParameter = function(keys, sourceURL){
    if ( typeof keys === 'string' ){
        keys = [keys];
    }

    var newURL; //Establish the scope

    jQuery.each(keys, function(index, item){
        var url = sourceURL;

        if ( typeof newURL !== 'undefined' ){
            url = newURL;
        }

        var baseURL = url.split('?')[0];
        var param;
        var params_arr = [];
        var queryString = ( url.indexOf('?') !== -1 )? url.split('?')[1] : '';

        if ( queryString !== '' ){
            params_arr = queryString.split('&');

            for ( i = params_arr.length-1; i >= 0; i -= 1 ){
                param = params_arr[i].split('=')[0];
                if ( param === item ){
                    params_arr.splice(i, 1);
                }
            }

            newURL = baseURL + '?' + params_arr.join('&');
        }
    });

    //Check if it is empty after parameter removal
    if ( typeof newURL !== 'undefined' && newURL.split('?')[1] === '' ){
        return newURL.split("?")[0]; //Return the URL without a query
    }

    return newURL;
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.removeQueryParameter = function(keys, sourceURL){
    //Write your own code here, leave it blank, or return false.
}