menu

Monday, October 21, 2013

Using JavaScript to extract GET parameters from URL query string


Hey guys,

So i was working on an awesome project when i wanted to extract GET parameters from the URL string. Like in php $_GET['param'], i need to use javascript since the front end is building on an REST API [that is no direct interaction between front end and back end].
You probably should ave seen this feature used in google search and may others, but the problem is JavaScript donot provide such function to access the parameters like PHP. After searching for ages i found dozen or more codes that were good, bad and unusable. But most of the code weren't much portable or user friendly. So i decided to make my own JS class for it :)

JsPara

Download from github
JsPara Homepage

Features

* Extract parameter=value pairs
  ex: index.html?search=test
* Extract null valued parameters
 ex: index.html?c&d
* Extract parameters followed by hash (#) (used in AJAX based sites)
 ex: index.html#search=test

Logic

JsPara simply use regular expression to find parameter=value pairs and then parameters with null value pairs.

Usage

Using JsPara is so damn easy. You just have to attach the script (which is only 2kb) and initiate a new JsPara object

For the sake of the tutorial, assume that the URL used here is
http://example.com/index.html?search=keyword&nothing&page=1#p=new

1) Initiate a JsPara object with window.location

 jp = new JsPara(window.location);
 //ex: http://example.com/index.html?search=keyword&nothing&page=1#p=new

2) To get all the extracted parameters [gives an array]

 var paras = jp.params;
 //output: search, page, p, nothing

3) To get value corresponding to a parameter

 var search = jp.param['search']
 //output: keyword

NOTE: Gives null if no value for the parameter

4) Get some other info about the URL

var hostname = jp.hostname; // example.com
var protocol = jp.protocol; // http
var path = jp.path; // example.com/index.html


Limitations

1) Some characters are not valid in the URL [since the regex breaks if those characters are present]

Valid parameter,value names

& and # are not allowed [you dont say :D]

test
test123
test_me
test me
test.me
"search"
[1,"abc",'def']
so that's basically it, but this is HIGLY BETA
so please please report me bugs and feature requests :)

Cyah

No comments:

Post a Comment