Search code examples
javascriptnavigation

Link to the next and previous page with Javascript


I have a pages with the links looks like this:

  • site.com/news/2015-01-12-8
  • site.com/news/2015-01-18-9
  • site.com/news/2015-02-02-10
  • site.com/news/2015-02-17-11

I need to change the last digit. For example...

Now I am on this page:

site.com/news/2015-02-02-9

So my next page link should be site.com/news/2015-02-02-10

And my previous page link should be site.com/news/2015-02-02-8

I want to make the page which will look like this

https://dl.dropboxusercontent.com/u/23508679/site-scr.png


Solution

  • I think you can store the current index of the image. You can extract the last digit using regular expression.

    JS code to extract last digits using image link :

    var currentIndex = parseInt("site.com/news/2015-01-12-8".match(/(\d+)$/g)[0]);
    

    and to get the previous and next link :

    var currentImageLink = "site.com/news/2015-01-12-8" // For example;
    var nextPageLink = "site.com/news/2015-01-12-8".replace(/\d+$/g, currentIndex+1);
    var previousPageLink = "site.com/news/2015-01-12-8".replace(/\d+$/g, currentIndex-1);
    

    Once you get the next and previous link, set the same to the previous and next anchor link.

    Hope it helps.