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 ?
location to Redirect to a Different URL with JavaScript. You can redirect a web page to another page in a number of ways including server-side redirects, HTML meta refresh redirects and JavaScript redirects.
history. pushState({page: "another"}, "another page", "example. html"); This will change the URL, but not reload the page.
replaceState() method The replaceState() is another method that updates the URL without reloading the page. It works exactly the same way as pushState() , but replaces the existing browser history entry instead of adding a new one.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With