Delete Query String Parameter in JavaScript - Quick & Easy

If you are working with query strings in JavaScript, you may find the need to remove a specific parameter from the URL. Fortunately, this task is quick and easy to accomplish with a few lines of code.

  1. The Solution:
  2. Usage Example:

The Solution:

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        params_arr = [],
        query_string = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (query_string !== "") {
        params_arr = query_string.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
        rtn = rtn + "?" + params_arr.join("&");
    return rtn;

The above code defines a function called removeParam that takes two parameters: key (the name of the parameter to remove) and sourceURL (the URL containing the parameter to remove). The function first splits the URL into two parts: the base URL without the query string and the query string itself. It then splits the query string into an array of parameters and iterates through each parameter to check if its name matches the key. If a match is found, the parameter is removed from the array. Finally, the function joins the remaining parameters back together and returns the modified URL.

Usage Example:

var url = "";
var newUrl = removeParam("param2", url);
console.log(newUrl); // ""

As you can see, the removeParam function returns a modified version of the original URL with the specified parameter removed. This solution is quick, easy to implement, and can save you a lot of time if you frequently work with query strings in your JavaScript code.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information