How do I read Javascript URL values (Querystring)?

Asked

Viewed 27,569 times

16

When accessing a page, for example

  • /item?tipo=1&nome=po%C3%A7%C3%A3o%20de%20cura

How do I get these URL values, decoding appropriately?

9 answers

8

To remove information from the url you can create an object with pairs of chave:valor of each url parameter.

In this case, it is seen that the parameter separator is the symbol & the values present are:

tipo=1
nome=po%C3%A7%C3%A3o%20de%20cura 
// "poção de cura" em versão está codificada para evitar caracteres não compatíveis com url, e evitar espaços brancos.

So depending on which library you use here are some examples:

Simple javascript:

function queryObj() {
    var result = {}, keyValuePairs = location.search.slice(1).split("&");
    keyValuePairs.forEach(function(keyValuePair) {
        keyValuePair = keyValuePair.split('=');
        result[decodeURIComponent(keyValuePair[0])] = decodeURIComponent(keyValuePair[1]) || '';
    });
    return result;
}
var myParam = queryObj();
console.log(myParam);

This gives: Object {tipo: "1", nome: "poção de cura"}

Note:

  • in javascript it is necessary to decode the string using decodeURIComponent()
  • once the query string starts with ?, I used the method splice() to remove the first character from the string.

In case you are using an older version of IE, and not browsers supporting Ecmascript5, use this version, instead of forEach():

for (var i = 0; i < keyValuePairs.length; i++) {
    keyValuePairs[i] = keyValuePairs[i].split('=');
    result[decodeURIComponent(keyValuePairs[i][0])] = decodeURIComponent(keyValuePair[1] || '');
};

Using a library like Mootools, makes it easier. so just need:

var myParam = window.location.search.slice(1).parseQueryString();
//retorna também: Object {tipo: "1", nome: "poção de cura"}

5

You can use a jQuery plugin: jQuery plugin Purl

Example of use:

1st import the Bibiloteca:

<script type="text/javascript" src="<caminho>/purl.js"></script>

To find the library just copy the code url.js,create a file named Purl.js and paste;

2º After importing the library you can choose to do it in two ways:

Using jQuery

var url = $.url('http://url.com.br/item?tipo=1&nome=po%C3%A7%C3%A3o%20de%20cura'); 
var tipo = url.param('tipo'); // valor do tipo = "1"
var nome = url.param('nome'); // valor do nome = "po%C3%A7%C3%A3o%20de%20cura"

No use jQuery

var url = purl('http://url.com.br/item?tipo=1&nome=po%C3%A7%C3%A3o%20de%20cura');
var tipo = url.param('tipo'); // valor do tipo = "1"
var nome = url.param('nome'); // valor do nome = "po%C3%A7%C3%A3o%20de%20cura"

4


You can use the following method:

// parametro `a` opcional, ex: `tipo=1&nome=espada#custo=0`
// o valor padrão é da URL atual
function GetQueryString(a)
{
    a = a || window.location.search.substr(1).split('&').concat(window.location.hash.substr(1).split("&"));

    if (typeof a === "string")
        a = a.split("#").join("&").split("&");

    // se não há valores, retorna um objeto vazio
    if (!a) return {};

    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        // obtem array com chave/valor
        var p = a[i].split('=');

        // se não houver valor, ignora o parametro
        if (p.length != 2) continue;

        // adiciona a propriedade chave ao objeto de retorno
        // com o valor decodificado, substituindo `+` por ` `
        // para aceitar URLs codificadas com `+` ao invés de `%20`
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    // retorna o objeto criado
    return b;
}

// uso
var qs = GetQueryString();

Thus its variable qs in the URL

  • /item?tipo=1&nome=po%C3%A7%C3%A3o%20de%20cura#tipo=2

will be

qs["tipo"];     // 2
qs["nome"];     // poção de cura
qs["nothere"];  // undefined (objeto)

It is worth noting that in this method if there is more than one parameter with the same name, only the last one will be considered.


Google method

Opening the Google code I found

function (b) {
    var c = typeof b === "undefined";
    if (a !== h && c) return a;
    for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
        var l = b[f][p]("=");
        if (l !== -1) {
            var q = b[f][I](0, l),
                l = b[f][I](l + 1),
                l = l[Ca](/\+/g, " ");
            try {
                d[q] = e(l)
            } catch (A) {}
        }
    }
    c && (a = d);
    return d
}

This minified, but it’s understandable.

The code looks for ? and # which is the point of the URL where the parameters appear. And for each parameter they divide by = using indexOf. If the parameter has value they add to the object. In the end the code takes care of the decoding and replaces + for .


Another option would be to use Regex to extract the values

4

function queryString(parameter) {  
              var loc = location.search.substring(1, location.search.length);   
              var param_value = false;   
              var params = loc.split("&");   
              for (i=0; i<params.length;i++) {   
                  param_name = params[i].substring(0,params[i].indexOf('='));   
                  if (param_name == parameter) {                                          
                      param_value = params[i].substring(params[i].indexOf('=')+1)   
                  }   
              }   
              if (param_value) {   
                  return param_value;   
              }   
              else {   
                  return false;   
              }   
        }

use

var id = queryString("id");

3

The previously presented functions perform poorly. I implemented two functions for this which are respectively 35% and 120% faster, they are part of the library Ideal.js:

// URL: http://exemplo.org/?nome=Arthur&sobrenome=Araújo
console.log(location.getQueryParam('sobrenome'))

// ou pode pegar todos os parâmentros de uma só vez:
var params = location.getQueryParams()
console.log('Nome', params['nome'])
console.log('Sobrenome', params['sobrenome'])

Function 1 - Location.getQueryParam():

window.location.getQueryParam = function(name, query) {

  if (!query) {
    query = window.location.search
  }

  var l = query.length
  var n = '' // name
  var v = '' // value
  var t = false

  for(var i=0; i<l; i++) {
    var c = query[i]

    if (c==='=') {
      t = true
    }
    else if (c==='&' || i===l-1) {

      if (n==name) {
        return decodeURIComponent(v)
      }

      t = false
      n = ''
      v = ''
    }
    else if (i>0 || c!=='?') {
      if (t) {
        if (c==='+') {
          c = ' '
        }
        v += c
      }
      else {
        n += c
      }
    }
  }
}

Function 2 - Location.getQueryParams():

window.location.getQueryParams = function(query) {

  if (!query) {
    query = window.location.search
  }

  var l = query.length
  var q = {} // query
  var n = '' // name
  var v = '' // value
  var t = false

  for(var i=0; i<l; i++) {
    var c = query[i]

    if (c==='=') {
      t = true
    }
    else if (c==='&' || i===l-1) {
      t = false
      q[n] = decodeURIComponent(v)
      n = ''
      v = ''
    }
    else if (i>0 || c!=='?') {
      if (t) {
        if (c==='+') {
          c = ' '
        }
        v += c
      }
      else {
        n += c
      }
    }
  }
  return q
}

You can see the difference in performance in mine case test.

3

If you want to use a framework, like jquery for example, you can use a plugin like this:

https://github.com/promatik/jQuery-Dynamic-URL (example of use here)

Allows you to do for example:

$.getVars(); 
> {"tipo" : 1, "nome" : "poção de cura"}

$.getVars().nome; 
> "poção de cura"

And even allows you to change the address bar by adding your own parameters in Runtime:

$.pushVar("genero", "medicina");
$.popVar("tipo");

The url would be:

/item?nome=po%C3%A7%C3%A3o%20de%20cura&genero=medicina

3

I looked up this same question in the English forum, and in this topic, has a very simple solution through an object called Urlsearchparams

The use is as follows::

const urlParams = new URLSearchParams(window.location.search);

const myParam = urlParams.get('myParam');

console.log(myParam)

The object is instantiated with the window.location.search, that delivers everything after URL interrogation

And finally using the method get by parameter name as argument, you can receive the value of the same

The caveat is that with this approach key parameters like: Filters[a], do not deliver the correct value through get

But for most cases, I believe this is an excellent way to redeem their values

2

function getUrlVars(){
 var vars = [], hash;
 var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 for(var i = 0; i < hashes.length; i++)
 {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
 }
 return vars;
}

I used so:

  • getUrlVars()["tipo"] returns "1"
  • getUrlVars()["nome"] returns "po%C3%A7%C3%A3o%20de%20cura"

1

I believe that most people looking for the answer to this question will be in the context of a web browser.

But for those who are using Node.js it is worth remembering that there is a native function for this:

> querystring.parse('tipo=1&nome=po%C3%A7%C3%A3o%20de%20cura')
{ tipo: '1', nome: 'poção de cura' }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.