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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • JavaScript Type Conversion and Coercion
  • JSON-Based Serialized LOB Pattern
  • Build a Java Microservice With AuraDB Free

Trending

  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • A Modern Stack for Building Scalable Systems
  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

By 
Douglas Rathbone user avatar
Douglas Rathbone
·
Jul. 20, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
16.1K 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.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • JavaScript Type Conversion and Coercion
  • JSON-Based Serialized LOB Pattern
  • Build a Java Microservice With AuraDB Free

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: