skip to Main Content

I want to dynamically change a specific parameter in the navigation bar.
I have this url and want to change "pedro" by "max":

http://mywebsite.com/?par1=mynameis&par2=pedro&par3=nicetomeetyou

By using this, it removes all my parameters.

hello = "max"
window.history.replaceState(null, null, "?par2="+hello);

This is what I want:

http://mywebsite.com/?par1=mynameis&par2=max&par3=nicetomeetyou

and not

http://mywebsite.com/?par1=mynameis&par2=max

3

Answers


  1. Use the URL interface

    const hello = 'max';
    // let url = new URL(location.href); // from location.href
    let url = new URL(`http://mywebsite.com/?par1=mynameis&par2=pedro&par3=nicetomeetyou`); // from string
    url.searchParams.set('par2',hello); // change ONE parameter
    console.log(url.searchParams.toString());
    window.history.replaceState(null, null, `?${url.searchParams.toString()}`);

    I prefer to start from the full URL but you can use the URLSearchParams instead

    const hello = 'max';
    // let sp = new URLSearchParams(location.search); // from location.search
    let sp = new URLSearchParams(`?par1=mynameis&par2=pedro&par3=nicetomeetyou`); 
    sp.set('par2',hello); // change ONE parameter
    console.log(sp.toString());
    window.history.replaceState(null, null, `?${sp.toString()}`);
    Login or Signup to reply.
  2. This may not be ideal, but it works.

    var newpar2 = "max"
    var newQueryStr = window.location.search.replace(/^(.+&par2=).+?(&.+)$/, `$1${newpar2}$2`)
    window.history.replaceState(null, null, newQueryStr);
    
    Login or Signup to reply.
  3. You can use URLSearchParams:

    const params = new URLSearchParams(window.location.search); // Creates search params object
    params.set('par2', hello); // Set par2 to new value
    window.history.replaceState(null, null, params.toString()); // Replace url
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search