Go4Expert

Go4Expert (http://www.go4expert.com/)
-   JavaScript and AJAX (http://www.go4expert.com/articles/javascript-tutorials/)
-   -   Using JavaScript to extract GET parameters from URL query string (http://www.go4expert.com/articles/using-javascript-extract-parameters-url-t29862/)

ManzZup 21Oct2013 19:59

Using JavaScript to extract GET parameters from URL query string
 
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
[COLOR="rgb(46, 139, 87)"]ex: index.html?c&d[/COLOR]
* Extract parameters followed by hash (#) (used in AJAX based sites)
[COLOR="rgb(46, 139, 87)"]ex: index.html#search=test[/COLOR]

Logic

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

The Code



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...g&page=1#p=new

1) Initiate a JsPara object with window.location

Code:

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]
Code:

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

3) To get value corresponding to a parameter
Code:

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

NOTE: Gives null if no value for the parameter

4) Get some other info about the URL
Code:

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]
Code:

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


All times are GMT +5.5. The time now is 12:05.