Skip to Content

removeQueryParameter()

Remove a query parameter from a string.

JavaScript February 7, 2021

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/modules/utilities.js on line 220.

No Hooks

This function does not have any filters or actions available. Request one?
JavaScript
nebula.removeQueryParameter = function(keys, url = location.search){
    //Convert single key to an array if it is provided as a string
    if ( typeof keys === 'string' ){
        keys = [keys];
    }

    let urlQuery = url;
    let baseURL = url.split('?')[0]; //Get the base URL (NOT including the "?" character)

    if ( url.indexOf('?') >= 1 ){ //If the location of the "?" character exists and is not the first character
        urlQuery = url.split('?').pop(); //Remove everything before the query string
    }

    let queryParameters = new URLSearchParams(urlQuery);

    jQuery.each(keys, function(index, item){
        queryParameters.delete(item);
    });

    let updatedQuery = decodeURIComponent(queryParameters.toString()); //Convert to string and decode the string

    //Return a string equivalent to the originally provided URL
    if ( url.indexOf('?') >= 1 ){ //If the location of the "?" character exists and is not the first character
        if ( updatedQuery.length > 0 ){ //If the query is not completely removed
            return baseURL + '?' + updatedQuery; //Append it to the original URL
        }

        return baseURL; //Otherwise, return the original URL
    }

    return updatedQuery; //Return just the query string alone
};

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.
}