Clear only a part of the URL

Asked

Viewed 64 times

1

I’m using a function to clear the URL, but I’d just like to clear a part of it.

    window.setTimeout(function() {
        window.history.replaceState(null, null, window.location.pathname);
    }, 5000);

For example the URL is ?id=1&msg=sc and I wanted to just leave ?id=1 how can I do this?

  • What are you doing this for? Wouldn’t it be better to just take directly the values of id and msg without having to do separations and replacements?

2 answers

0


It is possible using the split, you can separate your url by & and retrieve only the first parameter.

let url = "google.com?id=1&msg=sc"; // url
let urlSplit = url.split("&"); // cria um array separados por '&'
url = urlSplit[0]; // Recupera o primeiro item do array, no caso tudo antes do primeiro '&'

console.log(url);

If you want to take more than one parameter, just concatenate the parameters, getting something like this:

let url = "google.com?id=1&msg=sc&teste=123"; // url
let urlSplit = url.split("&"); // cria um array separados por '&'
url = `${urlSplit[0]}&${urlSplit[2]}`; // Recupera os items do array, concatenando por &

console.log(url);

  • I implemented in my code, in the console it works, but in the url of the browser remains the url, it would need to be done something to work?

  • Try the following: window.location.href = url

0

https://developer.mozilla.org/en-US/docs/Web/API/URL

var url = new URL(window.location.href)
url.searchParams.delete("msg")
history.replaceState(history.state, null, url.toString());

Idea demonstration (Chrome 49+, FF 29+):

var address = "http://google.com?id=1&msg=sc"
var url = new URL(address)
url.searchParams.delete("msg")
console.log(url.toString())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.