Good afternoon! How can I get only a part of a current url? For example, let's say I have the following url:
I would like to get only the value that comes after ?ip=
in this case dispensacao#15
Thank you
Good afternoon! How can I get only a part of a current url? For example, let's say I have the following url:
I would like to get only the value that comes after ?ip=
in this case dispensacao#15
Thank you
Use the Javascript split () function, like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var url = window.location.href;
url = url.split('?ip=');
url = url[1];
alert(url);
</script>
</body>
</html>
ES2015 (ES6)
const getParams = query => {
if (!query) {
return { };
}
return (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [ key, value ] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, { });
};
No jQuery
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
With the URL ?topic=123&name=query+string
, the return would be:
qs["topic"]; // 123
qs["name"]; // query string
qs["nothere"]; // undefined (object)
By default this javascript has this information in window.location
and to get the value, you can use the URL class.
var url = new URL(window.location);
var ip = url.searchParams.get("ip");
The value will be in the ip
variable.
The javascript function below returns an array / object with the parameters and values of the current url variables.
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;
}
Ex: http://leituracrista.com/audioplayer/player.html?ip=dispensacao#15&site=leituracrista
calling the getUrlVars () function, considering the url above, we will have the following return:
{
"ip" : "dispensacao#15",
"site" : "leituracrista"
}
To get the value of the first parameter would look like this:
var first = getUrlVars()["ip"]; //dispensacao#15
the second:
var second = getUrlVars()["site"]; //leituracrista
Try this, and the fence serves:
window.location.search