Capture parameters passed by url with javascript

May 18, 2020 • edited May 19, 2020

I did not like to pass variables with important data through the location bar for security reasons, but working on a project, I had to use javascript to capture the variables sent. Until then I had not needed the effect, so I searched - unsuccessfully - how to do it. The examples I found were useless to me, because they were very specific to the cases studied. Here is my version of how to capture such parameters.

Let’s look at the following example:

http://junihh.com/?usuario=junihh&nacionalidad=dominicano

The url consists of two parameters but in the way we will divide it we will be able to receive as many as are available, similar to how PHP’s “$ _GET” works. We also declare the “obj” variable that we will need later.

var loc = String(window.location.search).substring(1);
var obj = {}; 

We save the parameters in a string, taking as a reference the symbol “&” that is used to concatenate each key of the url.

var par = loc.split('&');

From this point on, the whole process will be simpler. We just need to iterate between all the parameters, saving the key / value in the “obj” variable.

for ( var i = 0, c = par.length; i < c; i++ )
{
    var p = par[i].split('=');
    obj[ p[0] ] = p[1];
};

Now let’s encapsulate everything in a function to use it comfortably in our projects:

function locationVars ()
{
    var loc = String(window.location.search).substring(1);
    var obj = {};

    if ( loc )
    {
        var par = loc.split('&');

        for ( var i = 0, c = par.length; i < c; i++ )
        {
            var p = par[i].split('=');
            obj[ p[0] ] = p[1];
        };
    };

    return obj;
};

Then we test it:

console.log( locationVars() );  
// RESPUESTA: {usuario: 'junihh', nacionalidad: 'dominicano'}

console.log( locationVars().usuario );  
// RESPUESTA: junihh

console.log( locationVars().nacionalidad );   
// RESPUESTA: dominicano

Ready. It can be served cold and with a lot of dressing. ;-)

JavaScript

Junihh

Junihh is talk about web-dev and opinion.

Follow these easy steps to react google login

Encrypt and decrypt text strings with PHP