How to change the current URL in javascript?

32

On my website:

http://mywebsite.com/1.html

I want to use the

window.location.pathname

to get the last part of the url:

1.html

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 = 'http://mywebsite.com/' + window.location.pathname;
function nextImage (){
url = url + 1;  
}

any ideas why this is not working ?

This question is tagged with javascript

~ Asked on 2012-01-14 23:07:28

The Best Answer is


31

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: http://jsfiddle.net/jfriend00/3VPEq/

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.

~ Answered on 2012-01-14 23:31:14


1

This is more robust:

mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');

When the URL has multiple numbers, it will change the last one:

http://mywebsite.com/8815/1.html

It supports numbers with leading zeros:

http://mywebsite.com/0001.html

Example

~ Answered on 2016-11-20 20:42:59


Most Viewed Questions: