Javascript + Do Not Make The Mistake Of Using Regex For Querystring / URL Params Handling

Assumptions:

  • The querystring key used throughout this article is named as niche
  • You know the basics of javascript and/or jQuery
  • This article makes use of jQuery, but you could just have used plain javascript.

At Glance => Handling Querystring or URL params through the use of Regex

Consider the following piece of code:

/**custom function to get querystrings from url
* Return values:
*              null         - when there is no querystring present
*              ""           - when querystring present without a value, example http://7php.com/?email=
*              results[1]   - value of querystring
*
* NOTE: This script has a shortcoming, with http://7php.com/?email, still the value is null which is not good
*        - The Pitfall we are discussing about in this article
*/

$.getParam = function(querystring)
{
	/// get querystring(s) without the ?
	var urlParams = decodeURI( window.location.search.substring(1) ); //NOTE: do not use unescape() for URI, use decodeURI()

	var result = new RegExp(querystring + '=([^&#]*)').exec( urlParams );
	if (!result)
		return null;
	else
		return result[1] || "empty string"; ///NOTE: replace "empty string" by "" - this was just to serve as a visual apercue
}

Let’s examine the different Scenarios the above code will handle:

1) URL with a querystring having a complete key/pair value:

Javascript querystring with key/pair value

Javascript querystring with key/pair value

This is the expected scenario and the code works just fine.

2) URL with a key + equal sign “=

Javascript Querystring - Returning Empty String

Javascript Querystring - Returning Empty String

Ok, with something like “niche=“, it is understood that the value should be an empty string or the test for a querystring is true. Though, the equal sign is not set like this when using a key-only situation, we should cope for it.

3) URL without a querystring
4) URL with only a key

Javascript Querystring - Execution returning NULL

Javascript Querystring - Execution returning NULL

Without a querystring, the result is as expected; null. But what about part 4) ? It should have been the same result as 2) above, is it? Right!
But why such a behaviour? Our regex has an equal sign in it, “=([^&#]*)“. Each time the code process the regex, it looks for a matching where there is an equal sign AND some characters.
You might be wondering we could circumvent this situation by perhaps modifying the regex in the ELSE part, but still it will not work and besides it’s kinda redundant.

Why You Should Not Use:

  • Due to the undesired pitfall mentioned in part 4)
  • Else, from a general point of view, if you have a choice between using regex or something else, by any means use that “something else”. Regex are expensive. For this example, since the code is client side, the cost of using regex is subtle, but still keep a habit of making the right choice.

Alternate way of handling URL params in javascript

In my next article, I will show you an alternate way of handling querystring with javascripts without using regex.

The Full Working Code – Download Free!

Here is a the full javascript code below, and you could download the whole package to try it on your pc, click here to download!

/**
* @author  : K_Wasseem
* @URL     : http://7php.com
* @license : FREE (like free air)
* @optional: I'll appreciate a link back from your site if you do refer to my article 😉
*/

(function($)
{
//register a ready event for our document, aka window.onload
$(document).ready(function()
{
var url = $.getParam("niche");
alert(url);
});

/**custom function to get querystrings from url
* Return values:
*              null         - when there is no querystring present
*              ""           - when querystring present without a value, example http://7php.com/?email=
*              results[1]   - value of querystring
*
* NOTE: This script has a bug, with http://7php.com/?email, still the value is null which is not good
*/
$.getParam = function(querystring)
{
//get querystring(s) without the ?
var urlParams = decodeURI( window.location.search.substring(1) );

var result = new RegExp(querystring + '=([^&#]*)').exec( urlParams );
if (!result)
return null;
else
return result[1] || "empty string"; ///NOTE: replace "empty string" by "" - this was just to serve as a visual apercue
}

})
(jQuery);

If You Appreciate What I Do Here On Seven PHP :: 7PHP, You Could Consider:

  1. Following me on Twitter | @7php
  2. LIKE-ing my FaceBook page
  3. Subscribe to my Email List - see top-right subscription box
  4. Help diffuse this interview to the PHP ecosystem - Share & Spread the word as far as you can ==> That would be a FREE way to thank me
  5. Use my DigitalOcean referral link if you plan to use it as your VPS (it starts at only $5/month btw) or if you can refer it to your friends, highly appreciated.
  6. Support via Paypal donate - my Paypal ID is w@7php.com

{I'm thankful to your response(s)!}

Trackbacks

  1. Tweets that mention Javascript + Do Not Make The Mistake Of Using Regex For Querystring / URL Params Handling « 7PHP dot COM -- Topsy.com says:

    […] This post was mentioned on Twitter by K_Wasseem, K_Wasseem and K_Wasseem, K_Wasseem. K_Wasseem said: Javascript + Using jQuery To Find URL QueryString or URL Params – A Simple, Yet Effective Approach! (http://bit.ly/dsyJ7O) […]

Speak Your Mind

*