Magician, Founder of indianmagicians.com n worldofmagicians.com , TV star, Software Engineer, Wikipedian, Actor, Skit Artist, Mimic Artist n lots..

Smart java script to handle query string using Regex

Handling query strings using java script is quite tough. If we Google it, we find lots of solutions, however most of the solutions are complicated or not generic. Years back I got one solution, but I have no idea who came up with this idea. The piece of code is totally generic and can be reused anywhere.


var uri = window.location.href; // Takes the current page Url
var queryString = {};           // array of querystring
uri.replace(
	new RegExp("([^?=&]+)(=([^&]*))?", "g"),
	function($0, $1, $2, $3) { queryString[$1] = $3; }
);                              //regex logic
// Alerts the firstName value from the query string
alert('First Name: ' + queryString['firstName']);
// Alerts the lastName value from the query string
alert('First Name: ' + queryString['lastName']);
 

Now imagine that the current page URL is
'http://www.geekphilip.com/add.php?firstName=philip&lastName=tiju&email=info@geekphilip.com'
Now by using queryString[ ‘tag Name’ ] you can read the value.
ie. queryString[‘firstName’] returns philip and queryString[‘lastName’] returns tiju.

I really would like to appreciate the guy, who came up with this idea.

Anyway Hats off to you boss.

7 Responses so far.

  1. john says:

    It works…
    just solved my problem…
    Thanks a million

  2. matt says:

    its quite simple and easy…

    Thanks a lot

  3. George says:

    Perfect…

  4. Juke says:

    Indeed its smart

  5. скачать says:

    Why is everything so difficult?,

  6. slot says:

    indeed its very smart

  7. Jessy says:

    This piece of code is very useful