DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. JavaScript
  4. Replacing Query String Elements in C# .NET and JavaScript

Replacing Query String Elements in C# .NET and JavaScript

Douglas Rathbone user avatar by
Douglas Rathbone
·
Jul. 20, 12 · Interview
Like (0)
Save
Tweet
Share
15.11K Views

Join the DZone community and get the full member experience.

Join For Free

While writing list navigation and search features in websites today there is a constant need to find/replace and play with query string elements, so that you can easily manipulate these mystical items while you’re carrying them around in your website’s URLs. I have a few little methods I’ve used over the years and carry with me project to project, and this post is putting them on the record for easy access later.

I have a secret. This post is actually more aimed at an audience of 'myself', and my ability to have an easy bit of source code to call upon when I’m on the go looking for a quick solution to cut and paste – as most of my blog posts are. But you, dear reader, you get to share in this benefit with me by pulling from the awesomeness within this post as well.

Solution: .Net c#

When doing this with c# you have a few pretty cool features up your sleeve. One of these is HttpUtility.ParseQueryString(urlPath) framework method. This static method allows you to extract a NameValueCollection that is editable from a given query string. Why is this cool? Because it allows you to very easily play with the query string collection like it is any other NameValueCollection – with Add() and Remove() methods. This makes it incredibly powerful.

Quick & Dirty code beware!

The code I’m pasting below is far from being the most elegant solution, i seem to have misplaced my nicer piece of code and am in too much of a rush to find it right now (sorry). Until i find my nicer solution, the method below will get you by – whether you have a hatred for ternary’s or not.

public static string ReplaceQueryStringParam(string currentPageUrl, string paramToReplace, string newValue)
{
    string urlWithoutQuery = currentPageUrl.IndexOf('?') >= 0 
        ? currentPageUrl.Substring(0, currentPageUrl.IndexOf('?')) 
        : currentPageUrl;

    string queryString = currentPageUrl.IndexOf('?') >= 0
        ? currentPageUrl.Substring(currentPageUrl.IndexOf('?')) 
        : null;

    var queryParamList = queryString != null 
        ? HttpUtility.ParseQueryString(queryString) 
        : HttpUtility.ParseQueryString(string.Empty);

    if (queryParamList[paramToReplace] != null)
    {
        queryParamList[paramToReplace] = newValue;
    }
    else
    {
        queryParamList.Add(paramToReplace, newValue);
    }
    return String.Format("{0}?{1}", urlWithoutQuery, queryParamList);
}

To call this, you can do the following:

// var currentUrl = HttpContext.Current.Request.Url;
var currentUrl = "http://www.mysite.com/mypage?category=cool-products&sort=price&page=3";

// change the my sort-by param named"sort" to "name"
var newUrlWithChangedSort = ReplaceQueryStringParam(currentUrl, "sort", "name");

Solution: JavaScript

The second part of this post includes a JavaScript solution, as you never know when you have to do this on the client side.

function replaceQueryString(url, param, value) 
{
    if (url.lastIndexOf('?') <= 0) url = url + "?";

    var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
    if (url.match(re))
        return url.replace(re, '$1' + param + "=" + value + '$2');
    else
        return url.substring(url.length - 1) == '?'
            ? url + param + "=" + value 
            : url + '&' + param + "=" + value;
}

And to use the above code in your client-side javascript simply write something along the lines of:

//var currentUrl = self.location;
var currentUrl = "http://www.mysite.com/mypage?category=cool-products&sort=price&page=3";

// change the my sort-by param named"sort" to "name"
var newUrlWithChangedSort = replaceQueryString(currentUrl, "sort", "name");

Easy – now next time you need to knock something together, instead of writing it yourself, you can simply cut & paste mine!

Database Strings Data Types JavaScript Element

Published at DZone with permission of Douglas Rathbone, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Handling Virtual Threads
  • Integration: Data, Security, Challenges, and Best Solutions
  • Explaining: MVP vs. PoC vs. Prototype
  • DevOps Roadmap for 2022

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: