How can I delete a query string parameter in JavaScript?
"[&;]?" + parameter + "=[^&;]+"
Seems dangerous because it parameter ‘bar' would match:
?a=b&foobar=c
Also, it would fail if parameter
contained any characters that are special in RegExp, such as ‘.'. And it's not a global regex, so it would only remove one instance of the parameter.
I wouldn't use a simple RegExp for this, I'd parse the parameters in and lose the ones you don't want.
function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts = url.split('?');
if (urlparts.length >= 2) {
var prefix = encodeURIComponent(parameter) + '=';
var pars = urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i = pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
}
return url;
}
Delete empty params from query string JS
It's less functional, but you can create a single URLSearchParams
object, then iterate over it and .delete
keys which have an empty value:
const queryString = "paymentMethod=1&fullname=&persona=&companyName=&countryName=&email=&totalCameras=&camerasOwned=&cameraShares=&snapmailCount=&sessionCount=&createdAtDate=&lastLoginAtDate=&telephone=&sort=created_at%7Cdesc&limit=50&page=1"
const params = new URLSearchParams(queryString);
[...params.entries()].forEach(([key, value]) => {
if (!value) {
params.delete(key);
}
});
const cleaned = String(params);
console.log(cleaned);
How to remove one specific query parameter from URL in Next.js?
You can call router.push
with the current query string, but omitting the search
parameter.
const params = new URLSearchParams(router.query);
params.delete('search');
const queryString = params.toString();
const path = `/${queryString ? `?${queryString}` : ''}`;
router.push(path, '', { scroll: false });
Given that you're currently at /?search=test&type=abc&category=xyz
, the above will route you to /?type=abc&category=xyz
. This will also handle scenarios where the type
and category
query parameters aren't present.
Remove querystring from URL
An easy way to get this is:
function getPathFromUrl(url) {
return url.split("?")[0];
}
For those who also wish to remove the hash (not part of the original question) when no querystring exists, that requires a little bit more:
function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}
EDIT
@caub (originally @crl) suggested a simpler combo that works for both query string and hash (though it uses RegExp, in case anyone has a problem with that):
function getPathFromUrl(url) {
return url.split(/[?#]/)[0];
}
Remove a Particular Query string from URL
Little bit of more search and then you can end up here:
var url = "www.foo.com/test?name=kevin&gender=Male&id=1234";
function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url= urlparts[0]+'?'+pars.join('&');
return url;
} else {
return url;
}
}
console.log(removeURLParameter(url, 'name'));
console.log(removeURLParameter(url, 'gender'));
Jsfiddle example
Related Topics
Hiding the Address Bar of a Browser (Popup)
How to Hide the Parent Div If All Its Child Div Are Hidden
How to Use If Statement Inside Json
Remove the Default Browser Header and Footer When Printing HTML
Javascript: Open Several Urls With One Button Click
Angularjs:Ng-Model Binding Not Updating When Changed With Jquery
How to Compare Two Json Have the Same Properties Without Order
How to Get Dynamic Id With Javascript/Jquery from PHP Loop
Why Does Google Chrome Always Add Space After Selected Text
How to Find Middle Element of Array in JavaScript
How to Disable Onclick Without Altering Its Function
Accessing Ejs Variable in JavaScript Logic
Force Browser to Download Image Files on Click
Accessing Variables from Other Functions Without Using Global Variables
Way to Access Const from Another Component in React