Maan Sahir Maan Sahir - 3 months ago 43
Javascript Question

How to change the current URL in javascript?

On my website:

I want to use the


to get the last part of the url:


and since I have all my webpages in numbers I want to add 1 to the current url so that when I click a button it will redirect me to the next page:

var url = '' + window.location.pathname;
function nextImage (){
url = url + 1;

any ideas why this is not working ?


Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);

You can then call it like this:

window.location.href = nextImage();

Demo here:

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.