Maan Sahir
Maan Sahir

Reputation: 369

How can I change the current URL in JavaScript?

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;
}

Why is this not working?

Upvotes: 32

Views: 120654

Answers (4)

j08691
j08691

Reputation: 208002

What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.

Why not do something like this:

var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';

nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.

Upvotes: 0

albanx
albanx

Reputation: 6333

Even if it is not a good way of doing what you want, try this hint:

var url = MUST BE A NUMBER FIRST

As in:

function nextImage () {
    url = url + 1;
    location.href = 'http://mywebsite.com/' + url + '.html';
}

Upvotes: 0

Zombo
Zombo

Reputation: 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

Upvotes: 1

jfriend00
jfriend00

Reputation: 708016

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.

Upvotes: 31

Related Questions