How to Delete a Query String Parameter in JavaScript

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



Leave a reply



Submit