How to Change the Url using JavaScript

this information is taken from

Question: 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 ?

Best answer:

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.

just check it 😉


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s