Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
Markdown Monster - The Markdown Editor for Windows

Get and Set Querystring Values in JavaScript


:P
On this page:

Lately that I’ve been working with ASP.NET MVC I’ve been finding myself in a few situations where I’ve needed to inject values into existing URLs. For example, when creating paging on a page it’s often useful to add a page number when the user clicks a page selection.

Imagine you have a url like this:

http://localhost/powerwell/search?subquerytype=sales&page=3&format=detail

and now you need to update the page number. You don’t know whether the page number is there or not or for that matter whether other parameters are present or not.

For example, in one case I have a search page with POST-able values on them and in order to inject the page number when clicking on one of the paging links does the following:

   <div class="pager">
     <% for (int i = 1; i <= Model.Paging.PageCount; i++){ %>        
        <a href="javascript: pageClick(<%= i %>);" class="pagebutton"><%= i%></a>
     <% } %>
    </div>     

    <script type="text/javascript">
        function pageClick(pageNo) {
            $("#form1")
                .attr("action","<%= Url.Action("search") %>" + 
setUrlEncodedKey("page",pageNo)) .submit(); } </script>

and this will always do the right thing updating or adding the page key with minimal fuss in code.

The JavaScript code basically modifies the form’s postback url by injecting the page query string variable into it and then forces the page to submit.

This isn’t the first time I’ve run into a situation where I needed to quickly read and then later write query string values on the client and so I created a couple of routines that read and set values in the query string:

getUrlEncodedKey = function(key, query) {
    if (!query)
        query = window.location.search;    
    var re = new RegExp("[?|&]" + key + "=(.*?)&");
    var matches = re.exec(query + "&");
    if (!matches || matches.length < 2)
        return "";
    return decodeURIComponent(matches[1].replace("+", " "));
}
setUrlEncodedKey = function(key, value, query) {
   
    query = query || window.location.search;
    var q = query + "&";
    var re = new RegExp("[?|&]" + key + "=.*?&");
    if (!re.test(q))
        q += key + "=" + encodeURI(value);
    else
        q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
    q = q.trimStart("&").trimEnd("&");
    return q[0]=="?" ? q : q = "?" + q;
}

There are a couple of helpers in use here. For completeness here they are as well:

String.prototype.trimEnd = function(c) {
    if (c)        
        return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
    return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function(c) {
    if (c)
        return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
    return this.replace(/^\s+/, '');
}

String.prototype.escapeRegExp = function() { return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0"); };

Both functions take a query string parameter as a string input that is optional. Leave out the query string and current query string from window.location is used instead. setUrlEncodedKey  always returns a query string value that has a leading ? whether you provided it or not on the input. It searches through keys and tries to locate an existing one. If found it’s replaced otherwise the value is appended to the end of the query string.

I’ve found these two routines useful as I’ve been updating some paging code I’ve been adding to a few applications and this definitely makes the job a lot easier. Hope some of you might find this useful as well.

Posted in JavaScript  

The Voices of Reason


 

Nicholas
September 07, 2009

# re: Getting and Setting Query String Values in JavaScript

Good post, but aren't you supposed to use "encodeURIComponent" rather than "encodeURI" ? As I understand it, encodeURI is meant to be run on the entire querystring itself, IE:

encodeURI('?myquery=string&is=nice&and=tidy')

Since it doesn't encode &, =, etc. but encodeURIComponent does.

http://xkr.us/articles/javascript/encode-compare/

Rick Strahl
September 07, 2009

# re: Getting and Setting Query String Values in JavaScript

@Nicholas - thanks and you're absolutely right. I fixed the code above. Thanks also for the great link that shows the differences very graphically, which apparently is something that I need to 'get it' :-}

Steve Gentile
September 07, 2009

# re: Getting and Setting Query String Values in JavaScript


DotNetShoutout
September 07, 2009

# Getting and Setting Query String Values in JavaScript - Rick Strahl

Thank you for submitting this cool story - Trackback from DotNetShoutout

Harvey
September 08, 2009

# re: Getting and Setting Query String Values in JavaScript

At the start, you talk about working in ASP.NET but strictly speaking this is client code, right? I think so long as one has jQuery linked into the client page, one could be working in WConnect or anyother server application. Would you agree?

Rick Strahl
September 08, 2009

# re: Getting and Setting Query String Values in JavaScript

@Jim - this is pure client code and it doesn't require jQuery. Just plop that into a page or library.

It's now part as ww.jquery.js so it'll be in the next drop of Web Connection.

Yan
December 15, 2009

# re: Get and Set Querystring Values in JavaScript

Thank you very much for this, Rick!

I was having a very bad time trying to capture my querystring values into a JS script, for an Ajax chat. The case is that my original code was working before, but then my boss asked me to convert it to code behind, and then the nightmare started!

Anyway, your cool functions turned everything easier.

Praveen
May 18, 2010

# re: Get and Set Querystring Values in JavaScript

Here is an example on how to replace the querystring in the given url:
http://praveenbattula.blogspot.com/2009/04/replace-querystrng-with-some-value-in.html

Christopher Deutsch
October 25, 2010

# re: Get and Set Querystring Values in JavaScript

Thank you for this! Just saved me some time. I owe you a beer!

BrainDrain
June 28, 2011

# re: Get and Set Querystring Values in JavaScript

How can your code can work if I see errors:
in escapeRegExp:
return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
must be
return this.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");

and q[0]=="?" doesn't work in some browsers? may be replaced with charAt(0)

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024