3

I have a URL like http://blog.com/post/1 and I need a function which updates the number at the end of it, for pagination.

So far I have:

window.location(document.URL++);
4
  • 1
    What is URL++ ? Is URL a variable name? Commented May 27, 2013 at 20:00
  • Please add more details. Commented May 27, 2013 at 20:05
  • @harsha No I was trying to use document.URL to get the current URL. Commented May 27, 2013 at 20:24
  • Not sure why this was voted down? Commented May 27, 2013 at 20:39

4 Answers 4

3
var url  = window.location.href.split('/'),
    page = parseInt(url.pop(), 10);

// to go to next page, increment page number and join with URL

window.location.href = url.join('/') +'/'+ (++page);

FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

0

You can do this with:

var url = document.URL;
var pagenumber = url.substr(url.length-1);
window.location = '/post/'+pagenumber++;

But it's a hacky, you can do your project struture better to don't need do this.

8 Comments

@sanjaypoyzer I don't know if getting the number on url is the best way to do. Becouse your code will be restricted to this format. If you need to change url, you need to change lots of code. And you can handle just 1 digit with this.
@sanjaypoyzer it does not handle pagenumbers with more than one digit.
incrementing the page number would be a good idea, no use in going to the same page ?
Ah it's definitely an issue that it doesn't handle pages with more than one digit. Can it be done without this fault?
Saving the worst for last, location is not a function !
|
0
var url = window.location.href; /* e.g. http://blog.com/post/1 */
var pagenumberString = url.match(/\d+/)[0];
window.location.href = url.substr(0, url.length - pagenumberString.length)
                       + (parseInt(pagenumberString, 10) + 1);

2 Comments

This seems to skip from 1 to 9 and then not do anything.
@sanjaypoyzer oops, minor mistake, forgot the + in the regexp. It is working now jsfiddle.net/Mellbourn/5NqsT
0

Increment the last number in URL (usually the page number) using a bookmark :

javascript:url=window.location.href;
newurl=url.replace(/(\d+)([^0-9]*)$/, function(t,x,y){return parseInt(x,10)+1+y});
window.location.href=newurl;

1 Comment

please format your code to increase the readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.