Contact   •   Products   •   Search

Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs

Get and Set Querystring Values in JavaScript


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.

Make Donation
Posted in JavaScript  


Feedback for this Post

 
# re: Getting and Setting Query String Values in JavaScript
by Nicholas September 07, 2009 @ 9:42am
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/
# re: Getting and Setting Query String Values in JavaScript
by Rick Strahl September 07, 2009 @ 2:01pm
@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' :-}
# re: Getting and Setting Query String Values in JavaScript
by Steve Gentile September 07, 2009 @ 7:10pm
# Getting and Setting Query String Values in JavaScript - Rick Strahl
by DotNetShoutout September 07, 2009 @ 11:36pm
Thank you for submitting this cool story - Trackback from DotNetShoutout
# re: Getting and Setting Query String Values in JavaScript
by Harvey September 08, 2009 @ 5:13am
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?
# re: Getting and Setting Query String Values in JavaScript
by Rick Strahl September 08, 2009 @ 9:59am
@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.
# re: Get and Set Querystring Values in JavaScript
by Yan December 15, 2009 @ 9:25am
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.
# re: Get and Set Querystring Values in JavaScript
by Praveen May 18, 2010 @ 9:42pm
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
# re: Get and Set Querystring Values in JavaScript
by Christopher Deutsch October 25, 2010 @ 12:23pm
Thank you for this! Just saved me some time. I owe you a beer!
# re: Get and Set Querystring Values in JavaScript
by BrainDrain June 28, 2011 @ 11:22pm
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 - 2014