Home > database >  Why url query component is not removed?
Why url query component is not removed?

Time:09-16

I wrap the href to URL, and try to remove one component, remove with delete, but component does not disappear. Do you know why?

let url = new URL(window.location.href);
let p = url.searchParams['postId' $(".selected").length];
delete p;
window.location = url.toString();

I tried this:

const filteredItems = url.searchParams.filter(key => url.searchParams[key] == postID);
let key = filteredItems.keys.first;
url.searchParams.delete(key);

but it says

Uncaught TypeError: url.searchParams.filter is not a function


I tried now this expression, but filter does not work, do you have any idea why?

function togglePost(postID) {
    let url = new URL(window.location.href);
    const filteredItems = Object.keys(url.searchParams).filter(key =>
        url.searchParams[key] == postID
    );
    let key = filteredItems.keys.first;

CodePudding user response:

The delete operator deletes properties from objects.

You are trying to delete a variable. This fails silently.

To delete something from a URLSearchParams object, use the delete method:

let url = new URL('http://example.com/foo.cgi?a=1&b=2');
console.log(url.toString());
url.searchParams.delete('a');
console.log(url.toString());

  • Related