Search code examples
javascripthtml5-history

prevent history.replaceState appending to the url


I am using window.history.replaceState and having some issues in that it keeps appending to the url.

It has been marked as a duplicate of this questionwhich I think is a mistake as when I use that code the same issue is occurring and it keeps appending the index to the url as described below.

Please see my code below:

let index = 1;

function incrementIndexAndUpdateUrl() {
   index++;
   window.history.replaceState('Object', 'Title', `${window.location.href }/${index}`);
}

The issue I am having is that the url keeps appending the number so it is doing something like the following:

https://slackoverflowz.com/questions/ask/2/3/4

Does anyone know how the code should look to update the url like as follows:

It is also worth noting the url is dynamic so I can't hardcode the path. I just want to update the index at the end of the url.


Solution

  • Since you are appending an /something, you are actually changing the pathname. So the easy way, is to store the original one before you do change it:

    let index = 1;
    const path = location.pathname;
    
    btn.onclick = incrementIndexAndUpdateUrl;
    
    function incrementIndexAndUpdateUrl() {
       index++;
       window.history.replaceState('Object', 'Title', `${path}/${index}`);
       console.log(location.href);
    }
    <button id="btn">increment</button>

    And as a fiddle for Chrome.