When I access a page, for example
-
/item?tipo=1&nome=po%C3%A7%C3%A3o%20de%20cura
How do I get these values from the URL by properly decoding?
When I access a page, for example
/item?tipo=1&nome=po%C3%A7%C3%A3o%20de%20cura
How do I get these values from the URL by properly decoding?
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();
In this way your qs
variable in the URL
/item?tipo=1&nome=po%C3%A7%C3%A3o%20de%20cura#tipo=2
will
qs["tipo"]; // 2
qs["nome"]; // poção de cura
qs["nothere"]; // undefined (objeto)
Note that in this method if there is more than one parameter with the same name, only the last one will be considered.
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
}
It's 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. At the end the code takes care of decoding and replaces +
with .
Another option would be to use Regex
to extract the values
To remove information from the url you can create an object with pairs of chave:valor
of each of the url parameters.
In this case, and once the parameter separator is the &
symbol, the values here 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 what 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:
?
, I used the splice()
method to remove the first character from the string. In case you are using an older version of IE, and not browsers that support 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 , it gets easier. so it only takes:
var myParam = window.location.search.slice(1).parseQueryString();
//retorna também: Object {tipo: "1", nome: "poção de cura"}
You can use a jQuery plugin: jQuery plugin Purl
Example usage:
1st Import to the library:
<script type="text/javascript" src="<caminho>/purl.js"></script>
To find the library, just copy the code purl.js , create a file with the name purl.js and paste;
2nd 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"
Not using 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"
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");
If you want to use a framework, such as jquery for example, you can use a plugin like this:
It 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 look like:
/item?nome=po%C3%A7%C3%A3o%20de%20cura&genero=medicina
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 this way:
getUrlVars()["tipo"]
returns "1"
getUrlVars()["nome"]
returns "po%C3%A7%C3%A3o%20de%20cura"
The functions listed above perform poorly. I have implemented two functions for this which are respectively 35% and 120% faster , they are part of the 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 performance difference in my case test .
I believe most of the people who are looking for the answer to this question will be in the context of a web browser.
But for anyone using node.js it's 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' }