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

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

  • Identity in Action
  • Implementing Observability in Distributed Systems Using OpenTelemetry
  • Prompt Injection Is Real, So I Built a Python Firewall for LLM Pipelines
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  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.5K 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. 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.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook