HTML GET values in Javascript

Reads the values from url, using function name for previous php programmers.

// gerUrlVars from http://papermashup.com/read-url-get-variables-withjavascript/ modified to correct some errors in the code.
function $_GET() {
    "use strict";
    var vars = {}, parts = window.location.href.replace(/[?&]+([^=&]+)=([^&#]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}

Major change on this version is the regex that is adapted to support Anchor links (hash tags in url).
http://url?search=test#subsection

var value = $_GET.search;
if (typeof value !== "undefined") { // checks that value has been set, prevents error for trying to read undefined value.
    alert(value);
}

alerts “test”

This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

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