JavaScript Parse URI Script

Recently (and in the past) I have needed a way to get URL query string variables with JavaScript.  This simple script regular expression (regex) in JavaScript will allow you to get query variables out of the URL with ease.  A function should come of this but I wanted to post a simple version to get it out there.  On to the code:

1
2
var matches = location.search.match(/getvar=([^&?]*)/);
var getvar = $matches[1]

Enjoy!

Update:

Although the script above does work, this is a little more practical. Disclaimer: I did not write the code below, but I do not have the resource from which I stumbled upon.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @param q string the URI variable you are trying to retrieve
* @param s string the URL that contains the URI variable
*/
function _GET(q,s)
{
    var s = s ? s.replace('/?', '') : window.location.search.substring(1); 
    var vars = s.split("&"); 
 
    for (var i = 0; i < vars.length; i++)
    {
        var pair = vars[i].split("=");
        if (pair[0] == q)
        {
            return unescape(pair[1]);
        }
    }
 
    return undefined;
}
 
/**
* Sample usage
*/
var company_name = decodeURIComponent(_GET('company_name', $(this).attr('href')));
Tagged with: , , , ,
Posted in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>