Search code examples
javascriptjqueryhtmlcssweb

window.location.href appending instead of replacing


I have a little issue that I couldn't figure out. I have a slider and I want to change url when I click prev and next buttons. Here are my codes below but it doesn't work correctly. Every time I click the button, url appending instead of replacing.

var url = window.location.href;
url = url + "page/" + 1;  // this number is dynamic actually
window.location.href = url;

For instance it displays; stackoverflow.com/page and I clicked stackoverflow.com/page/1 and again stackoverflow.com/page/1/page/2

But I just want to replace it stackoverflow.com/page/1 to stackoverflow.com/page/2

How can I fix it? Thank you for your help.


Solution

  • window.location.href returns the entire url...

    if you just want to add the "/page/1"

    use

    var url = window.location.origin;
    url = url + "/page/" + 1;  // this number is dynamic actually
    window.location.href = url;
    

    though window.location.origin is undefined in windows 10

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

    you could just replace the /page/#number#

    var url = window.location.href;
    url = url .replace(new RegExp("/page/[0-9]"), "/page/2")
    window.location.href = url;