Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the current URL in javascript?

Tags:

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

any ideas why this is not working ?

like image 581
Maan Sahir Avatar asked Jan 14 '12 23:01

Maan Sahir


People also ask

Can we change URL using JavaScript?

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.

How do I use JavaScript to modify the URL without reloading the page?

history. pushState({page: "another"}, "another page", "example. html"); This will change the URL, but not reload the page.

How do I change URL without reloading?

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.


1 Answers

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.

like image 159
jfriend00 Avatar answered Oct 04 '22 18:10

jfriend00