Tuesday, March 8, 2016

Incrementing a numeric query parameter in C#

If you have webpages that implement paging, you may need to build <link rel=”next/prev” metatags to help search engines index your website.  Depending on the way you implemented the paging, you’ll generally have some version of indicating the current page in the querystring of the url.  To get the next/prev links relative to this page, you’ll generally just need to increment or decrement the pageNumber querystring value.  Below is an example of how to use Regex to increment that querystring parameter.

var pageUrl = "http://mywebsite.com/info?page=5&items=15";
var reMatch = @"page=(?\d+)";
var newUrl  
    = System.Text.RegularExpressions
    .Regex.Replace( 
    pageUrl, 
    reMatch,
    (m) =>
    {
        string sPage = m.Groups["PageNumber"].Value;
        int iPage = Convert.ToInt32(sPage);
        return "page=" + (iPage + 1).ToString();
    });

// Results: newUrl = "http://mywebsite.com/info?page=6&items=15";

No comments:

Post a Comment