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 question which 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.
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>
You should do it from window.location.origin and start appending the pathname, so probably your answer would be
let index = 1;
function incrementIndexAndUpdateUrl() {
index++;
window.history.replaceState('Object', 'Title', `${window.location.origin}/question/ask/${index}`);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.