How to find the parameter key from window location path? - javascript

I have query string is as follows.
Window.location.href = http://192.168.1.25:9990/myprofile?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs
I am trying window.location.search I am getting ?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs
But expected output : IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs I need without ?

Try:
window.location.search.substring(1)

You can use searchParams.get() like this example :
var currentUrl = Window.location.href;
var url = new URL(currentUrl);
var c = url.searchParams.get("myprofile");
Check this link

var urlStr = "http://192.168.1.25:9990/myprofile?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs";
function getqueryString(url) {
var retObj = {};
if (!url) return retObj;
var str = url.split('?')[1];
if (!str) return retObj;
var query = str.split('&');
for (var i = 0; i < query.length; i++) {
var pair = query[i].split('=');
retObj[pair[0]] = pair[1];
}
return retObj;
}
var rsl = getqueryString(urlStr);
console.log(rsl)
You can use this function it takes URL as the parameter and returns Back all the query parameter in an object form

Related

How can I put all the URL parameters in array of objects using jQuery?

I have a giving string/url like this
https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables
I need to loop thought each parameter in the url. If the value starts with : this indicated that it is a variable an I will need to change that value dynamically by looking at the corresponding meta attribute that matches that variable.
Here is my code in which loops over an array and sets the value of the parameters.
var baseURL = getBaseURL(url);
var params = getParams(url);
var newParams = $.each(params, function(index, param){
if( param.value.substring(0, 1) == ':'){
var myVar = param.value.substring(1);
param.value = $('meta[name=" + myVar + "']).attr('value');
}
});
var finalURL = baseURL + '?' + jQuery.param( newParams );
function getParams(url){
// This function should return an array of objects. Each object should have 2 properties "value" and "name". The "name" property should be the name of the parameter (ie. var1, var2, var3 .....) and the "value" attribute should contains the value of the parameter (ie. 100, :somevar, :morevariables)
}
function getBaseURL(url){
var cutoff = url.indexOf('?');
if( cutoff > -1){
return url.substring(0, cutoff - 1);
}
return url;
}
I need help converting the parameters of a giving URL to array of object. How can I do this in jQuery?
You dont need jQuery for this one.
function getParams(url) {
var queryString = url.substring(url.indexOf('?') + 1);
var paramsArr = queryString.split('&');
var params = [];
for (var i = 0, len = paramsArr.length; i < len; i++) {
var keyValuePair = paramsArr[i].split('=');
params.push({
name: keyValuePair[0],
value: keyValuePair[1]
});
}
return params;
}
Here is an example using map
var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables&test';
function getParamArray(url) {
var queryString = url.substring(url.lastIndexOf("?") + 1);
return queryString.split('&').map(function(sParam) {
var param = sParam.split('=');
return {
name: param[0],
value: decodeURIComponent(param[1])
};
});
}
document.getElementById("output").innerHTML = JSON.stringify(getParamArray(url), null, 2);
<pre id="output"></pre>
With a regular expresion and JSON.parse:
var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables';
url = url.replace(/^.*\?/,'');
url = url.replace(/(\w+)=?([\w:]*)/g,'{"name":"$1","value":"$2"}');
url = url.replace(/&/g,',');
var paramsObject = JSON.parse("["+url+"]");
/*
Returns:
Array [{"name":"var1","value":"100"},{"name":"var2","value":":somevar"},{"name":"var3","value":":morevariables"}];
*/
You don't even need JQuery for this.
<script type="text/javascript">
var paramStr = window.location.search;
var params = paramStr.substring(1, paramStr.length).split('&');
var paramList = [];
for (var index=0; index < params.length; index++) {
var param = params[index].split('=');
paramList.push({name: param[0], value: param[1]});
}
</script>
The result:
[Object]0: Object
name: "a"
value: "b"
...
var url=new URLSearchParams(window.location.search);
var params = [];
for(var value of url.keys())
{
params.push({
name: value,
value: url.get(value)
});
}

Prase query string from url javascript

my url look like http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1
now i am looking for a function where i will pass url and query string name then that should return value.
so i did it this way but not working.
function getQueryVariable(url,variable) {
var query = url;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
calling like this way
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert(getQueryVariable(x,'sort'));
alert(getQueryVariable(x,'sortdir'));
alert(getQueryVariable(x,'page'));
where i made the mistake?
EDIT
working code
$.urlParam = function(url,name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert($.urlParam(x,'sort'));
alert($.urlParam(x,'sortdir'));
alert($.urlParam(x,'page'));
https://jsfiddle.net/z99L3985/1/
thanks
may be the following will help
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1';
var queryVars = getUrlVars(x);
alert(queryVars['sort']);
alert(queryVars['sortdir']);
alert(queryVars['page']);
I just get this from somewhere else as well..
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
console.log(vars);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] === variable){return pair[1];}
}
return(false);
}
so far its doing its job.
with url: "http://urlhere.com/general_journal?from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2"
if im going to get the 'page' variable result would be : `2`
console.log(getQueryVariable('page'));
my query variable is only getting the search.substring(1) part of the the url so basically it only gets from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2 part of the url then from that it splits it and then return the value of the string parameter you specified on the function call getQueryVariable('page') for example.
Maybe this helps
var getUrlVars = function(url){
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == url){
vars =[];
}
return vars;
}
Then in your code
var params = getUrlVars("http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1");
console.log(params["sort"]) // FirstName

Javascript location.search

How could I specifically get every of these query strings in
file:///K:/CKaing_C20_A01_Casino2/game.html?First+Name=Testfirst&Last+Name=Testlast&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000
For example, I want to get Testfirst, and then assign it to a variable so I can use it later on. Same thing with the others.
This is what I have so far to remove all the +, =
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
for (var i=0; i < formArray.length; ++i) {
document.writeln(formArray[i] + "<br />");
}
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/\=/g,"\"\:\"").replace(/\&|(\/\?)/g,"\", \""))+"\"}")
I made that one for a webpage that uses a rare ("/?") separator too.
http://example.com/?a=0&b=bee/?c=third
First one will work for URLs like that
If you want it for a conventional location:
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/\=/g,"\"\:\"").replace(/\&/g,"\", \""))+"\"}")
Once splitSearch is defined you can get "pnum" string like this:
splitSearch.pnum
splitSearch["pnum"]
Another way to get it:
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/(\=)|(\&)|(\/\?)/g, function(k) {
var rtn=k;
if (k == "\=") rtn="\"\:\"";
else if ((k == "\&") /*|| (k == "\/\?")*/) rtn="\",\"";
return rtn;
})+"\"}"))
A mix of use of replace with regEx and the split function does the work.
var str = "file:///K:/CKaing_C20_A01_Casino2/game.html?
First+Name=Testfirst&Last+Name=Testlast
&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000";
var argStrIndex = str.indexOf("?");
var argStr = str.substring(argStrIndex+1);
var args = argStr.replace(/\+/g," ").split("&");
for (var i=0;i<args.length;i++){
alert(args[i]);
}
demo: http://jsfiddle.net/7meAv/
something like that :
var search = location.search
.replace(/^\?/,'')
.replace(/\+/g,' ')
.split('&')
.map(function(string){
var split = string.split('=');
var res={};
res[split[0]]=split[1];
return res;
});
should return
[{"First Name":"Testfirst"},{"Last Name":"Testlast"},{"pnum":"123-456-7890"},{"postCode":"A1A 1A1"},{"startMoney":"5000"}]"
You'd need to take care of url encoding though.
A combination of the two answers already given (jsfiddle: http://jsfiddle.net/russianator/GymEq/)
var url = 'file:///K:/CKaing_C20_A01_Casino2/game.html?First+Name=Testfirst&Last+Name=Testlast&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000';
queryObject = {};
url.substring(url.indexOf('?')+1)
.replace(/\+/g,' ')
.split('&')
.forEach(function(item) {
splitItem = item.split('=');
queryObject[splitItem[0]] = splitItem[1];
});
Returns an object like this:
{
"First Name": "Testfirst",
"Last Name": "Testlast",
...
}

How to get an url contained in query string

I want a javascript variable to be what is behind the ?url= in the url..
for example: The current url is
http://mywebsite.com/test/index.html?url=http://www.google.com/
So the variable has to be http://www.google.com/ .
I tried this, but it doesn't work… why ?
var url = document.URL ;
var appname = url.match(?url=(.+))[1];
Thanks.
I think the following will work for you:
function querystring(key) {
var query = window.location.search.substring(1);
var keys = query.split("&");
for (i = 0; i < keys.length; i++) {
var values = keys[i].split("=");
if (values[0] == key) {
return values[1];
}
}
}
var appname = querystring("url");
alert(appname);
Try this:
var regex = /\?url\=(.+)/;
var appname = regex.exec(url)[1];
or even simpler:
var appname = /\?url\=(.+)/.exec(url)[1];
var url = location.search.match(/url=([^&]+)&*.*$/)[1]; // http://www.google.com/
location //location object
.search //the search part in location
.match //return string according to regex given
[1] //second result (result in parenthesis)
//--------Use in a function---------
function getQuery(txt){
var result = location.search.match(new RegExp(txt + "=([^&]+)&*.*$"));
return result === null ? undefined : result[1];
}
http://jsfiddle.net/DerekL/J4FfZ/

scrape id from url using javascript

I have the following URL:
http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE%2527S%2BGARDEN.
Where bi is a identifier for the specific book.
How can I extract the book id from the link?
Thanks!
You can to use this regex:
var address = "http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&...";
var bi = /[\?&]bi=(\d+)/.exec(address)[1]
alert(bi)
function getBookId()
{
var query = document.location.split("?")[1];
var values = query.split("&");
for(var i = 0; i < values.length; i++)
{
a = values[i].split("=");
if(a[0] === "bi")
return a[1];
}
//some error occurred
return null;
}
You can extract the book id (assumed to be only numbers) via a regular expression (and grouping).
var s = "http://www.abebooks.com/servlet/BookDetailsPL?\
bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.\
%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE\
%2527S%2BGARDEN."
var re = /bi=([0-9]+)&/; // or equally: /bi=(\d+)&/
var match = re.exec(s);
match[1]; // => contains 1325819827
address.split("bi=")[1].split("&")[0]
Try this
var bookId
var matcher = location.search.match(/(?:[?&]bi=([^&]+))/); // Assuming window.location
if (null !== matcher) {
bookId = matcher[1];
}
I once had the same problem.
I created a little function to help me out. Don't know where it is but I managed to recreate it:
function get(item,url) {
if (url == undefined)
url = window.location.href;
var itemlen = item.length
var items = url.split('?')[1].split('&');
for (var i = 0, len = items.length;i<len;i++) {
if (items[i].substr(0,itemlen) == item)
return items[i].split('=')[1];
}
return null;
}
So you would use it like:
get('bi');
If the url you gave was your current url, if not you could do:
get('bi','http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE%2527S%2BGARDEN.')
Hope I didn't leave in any bugs :)

Categories

Resources