Search code examples
javascripturlhrefpushstate

Replace only last path part in URL not parametres


I can change the last part (in the URL: child) of the URL, but if the URL's parameters exist, these parameters are deleted by this change (?para=1&para=2).

Is there a way to not delete the parameters?

Sample:

https://example.com/sub/child?para=1&para=2

JS:

const str = window.location.href;
const lastIndex = str.lastIndexOf("/");
const path = str.substring(0, lastIndex);
const new_path = path + "/new_child";
window.history.pushState("object or string", "Title", new_path);
window.history.replaceState("object or string", "Title", new_path);

Solution

  • Before replacing the last part you can save the parameters like this

    var str = "https://example.com/sub/child?para=1&para=2";
    var params = str.split('?')[1]
    const lastIndex = str.lastIndexOf("/");
    const path = str.substring(0, lastIndex);
    const new_path = path + "/new_child?"+params;
    console.log(new_path)

    Alternatively you can create a function to do this using regex

    var str = "https://example.com/sub/child?para=1&para=2";
    const new_path = replaceUrlPart(str, "child", "new_child")
    console.log(new_path)
    
    function replaceUrlPart(url, partToRemove, partToAdd){
     return url.replace(partToRemove,partToAdd);
    }