10 March 2016

Working with GET-Parameters

 Introduction

 Working with Get-Parameters from the url can be very usefull. Recieving those parameters can be a pain in the ass. Here is a simple function that does the trick. So if you want to know the value of the parameter "q", it's in param("q").

Arguments

 The name of the parameter to search for

Returns 

 The value of the parameter (undefined, if the parameter is not existend or empty)

 Requirements

This function doesn't require anything then JS itself. Can even work without jQuery.

Code

 function param() {
    var searchstring = window.location.search;
    if (!searchstring) {
        // search is empty
        return undefined;
    }
    // search 
    var part = searchstring.search("&" + arguments[0] + "=");
    if (part == -1) {
        part = searchstring.substring(1).search(arguments[0] + "=");
        if (part == -1) {
            return undefined;
        }
    }
    // found!
    searchstring = searchstring.substring(part + 1);
    part = searchstring.search(/&/);
    if (part > -1) {
        searchstring = searchstring.substring(0, part);
    }
    part = searchstring.search(/=/);
    searchstring = searchstring.substring(part + 1);
    return searchstring;
}

No comments:

Post a Comment