[javascript] Using the GET parameter of a URL in JavaScript

If I am on a page such as

http://somesite.com/somepage.php?param1=asdf

In the JavaScript of that page, I would like to set a variable to the value of the parameter in the GET part of the URL.

So in JavaScript:

<script>
   param1var = ...   // ... would be replaced with the code to get asdf from URI
</script>

What would "..." be?

This question is related to javascript url get

The answer is


I made this variation of gnarf's solution, so the call and the result is similar to PHP:

function S_GET(id){
    var a = new RegExp(id+"=([^&#=]*)");
    return decodeURIComponent(a.exec(window.location.search)[1]);
}

But as being called in a function slows the process, its better to use as global:

window['var_name'] = decodeURIComponent( /var_in_get=([^&#=]*)/.exec(window.location.search)[1] );

UPDATE

As I'm still learning JS, I created a better answer in a more JS behaviour:

Url = {
    get get(){
        var vars= {};
        if(window.location.search.length!==0)
            window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
                key=decodeURIComponent(key);
                if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
                else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
            });
        return vars;
    }
};

This allows to be called just using Url.get.

Example The url ?param1=param1Value&param2=param2Value can be called like:

Url.get.param1 //"param1Value"
Url.get.param2 //"param2Value"

here is a snipet:

_x000D_
_x000D_
// URL GET params_x000D_
url = "?a=2&a=3&b=2&a=4";_x000D_
_x000D_
Url = {_x000D_
    get get(){_x000D_
        var vars= {};_x000D_
        if(url.length!==0)_x000D_
            url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){_x000D_
                key=decodeURIComponent(key);_x000D_
                if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}_x000D_
                else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}_x000D_
            });_x000D_
        return vars;_x000D_
    }_x000D_
};_x000D_
_x000D_
document.querySelector('log').innerHTML = JSON.stringify(Url.get);
_x000D_
<log></log>
_x000D_
_x000D_
_x000D_


If you're already running a php page then

php bit:

    $json   =   json_encode($_REQUEST, JSON_FORCE_OBJECT);
    print "<script>var getVars = $json;</script>";

js bit:

    var param1var = getVars.param1var;

But for Html pages Jose Basilio's solution looks good to me.

Good luck!


From my programming archive:

function querystring(key) {
   var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
   var r=[], m;
   while ((m=re.exec(document.location.search)) != null) r[r.length]=m[1];
   return r;
}

If the value doesn't exist, an empty array is returned.
If the value exists, an array is return that has one item, the value.
If several values with the name exists, an array containing each value is returned.

Examples:

var param1var = querystring("param1")[0];

document.write(querystring("name"));

if (querystring('id')=='42') alert('We apoligize for the inconvenience.');

if (querystring('button').length>0) alert(querystring('info'));

You don't need to do anything special, actually. You can mix JavaScript and PHP together to get variables from PHP straight into JavaScript.

var param1val = '<?php echo $_GET['param1'] ?>';

Here is a version that JSLint likes:

/*jslint browser: true */
var GET = {};
(function (input) {
    'use strict';
    if (input.length > 1) {
        var param = input.slice(1).replace(/\+/g, ' ').split('&'),
            plength = param.length,
            tmp,
            p;

        for (p = 0; p < plength; p += 1) {
            tmp = param[p].split('=');
            GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
        }
    }
}(window.location.search));

window.alert(JSON.stringify(GET));

Or if you need support for several values for one key like eg. ?key=value1&key=value2 you can use this:

/*jslint browser: true */
var GET = {};
(function (input) {
    'use strict';
    if (input.length > 1) {
        var params = input.slice(1).replace(/\+/g, ' ').split('&'),
            plength = params.length,
            tmp,
            key,
            val,
            obj,
            p;

        for (p = 0; p < plength; p += 1) {
            tmp = params[p].split('=');
            key = decodeURIComponent(tmp[0]);
            val = decodeURIComponent(tmp[1]);
            if (GET.hasOwnProperty(key)) {
                obj = GET[key];
                if (obj.constructor === Array) {
                    obj.push(val);
                } else {
                    GET[key] = [obj, val];
                }
            } else {
                GET[key] = val;
            }
        }
    }
}(window.location.search));

window.alert(JSON.stringify(GET));

Using jquery? I've used this before: http://projects.allmarkedup.com/jquery_url_parser/ and it worked pretty well.


You can use this function

function getParmFromUrl(url, parm) {
    var re = new RegExp(".*[?&]" + parm + "=([^&]+)(&|$)");
    var match = url.match(re);
    return(match ? match[1] : "");
}

You can get the "search" part of the location object - and then parse it out.

var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];

Here's how you could do it in Coffee Script (just if anyone is interested).

decodeURIComponent( v.split( "=" )[1] ) if decodeURIComponent( v.split( "=" )[0] ) == name for v in window.location.search.substring( 1 ).split( "&" )

This looked ok:

function gup( name ){
   name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regexS = "[\\?&]"+name+"=([^&#]*)";
   var regex = new RegExp( regexS );
   var results = regex.exec( window.location.href );
   if( results == null )
      return "";
   else
      return results[1];
}

From http://www.netlobo.com/url_query_string_javascript.html


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to get

Getting "TypeError: failed to fetch" when the request hasn't actually failed java, get set methods For Restful API, can GET method use json data? Swift GET request with parameters Sending a JSON to server and retrieving a JSON in return, without JQuery Retrofit and GET using parameters Correct way to pass multiple values for same parameter name in GET request How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Making href (anchor tag) request POST instead of GET?