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.
The Solution:
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
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 = "https://www.example.com/page?param1=value1¶m2=value2¶m3=value3";
var newUrl = removeParam("param2", url);
console.log(newUrl); // "https://www.example.com/page?param1=value1¶m3=value3"
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.
Leave a Reply
Related posts