How to set a comma sep. string as a paramter? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I get query string values?
ive a a function call like:
var ex = _.where(obj, {param1:0,param2:1});
which works fine, all the code behind.
I check my URL and take out the parameters and save this information into a array:
var query = window.location.search.substring(1);
var vars = query.split("&");
var testParamter = vars.toString().replace( /=/g,':' );
that return by using console.log(testParamter); the following result:
param1:0,param2:1
but i cant insert yet the var testParamter into my function call:
var ex = _.where(obj, {testParamter});
because it is a string and i cant handel it with eval(). so can anyone tell me please the right way to solve it?
thanks

Iterate over the values from the querystring and create an object from those values :
var query = window.location.search.substring(1),
vars = query.split("&"),
params = {};
$.each(vars, function(k,v) {
var arr = v.split('=');
params[ decode(arr[0]) ] = decode(arr[1]);
});
var ex = _.where(obj, params);
function decode(s) {
return decodeURIComponent(s.replace(/\+/g, " "));
}

Related

How to get an array from the URL? [duplicate]

This question already has answers here:
Get the values from the "GET" parameters (JavaScript) [duplicate]
(63 answers)
How can I convert a comma-separated string to an array?
(19 answers)
How to obtain the query string from the current URL with JavaScript?
(19 answers)
Closed 4 years ago.
I have put an array into my URL like this:
var params = arrayitems.join('&');
var url = "https://www.example.com/page?="+params;
So the URL looks like this:
https://www.example.com/page?=item1&item2&item3&item4&item5
Now does anyone know how I can then put these items back into an array on the next page?
Thanks!
You can split them back by page?= and than &
let arrayitems = ['item1','item2','item3','item4','item5']
var params = arrayitems.join('&');
var url = "https://www.example.com/page?="+params;
let arrayBack = url.split('page?=')[1].split('&')
console.log(arrayBack)
URL Object:
Use URL to get the data you need from the search parameters.
URL is used to parse, construct, normalise, and encode URLs.
The URL object has a very convenient method called searchParams
The searchParams readonly property of the URL interface returns a
URLSearchParams object allowing access to the GET decoded query
arguments contained in the URL.
Quick solution:
not recommended... but works
Since your query parameters are not valid (no key, just values) an extra step is required to get the values.
const url = new URL('https://www.example.com/page?=item1&item2&item3&item4&item5');
const res = [...url.searchParams]
.flat()
.filter(v=>v!==null&&v.length>0);
console.log(res);
Better solution using valid URL:
It would be better if you instead organised your URL the following way, so that your url string would look like
https://www.example.com/page?item=item1&item=item2&item=item3
const params = ['item1','item2','item3']
.map(v=>'item='+v)
.join('&');
const urlStr = "https://www.example.com/page?"+params;
const url = new URL(urlStr);
//Two possible ways of getting the values
//Option 1
const resOption1 = url.searchParams.getAll('item');
//Option 2
const resOption2 = [...url.searchParams.values()];
console.log(resOption1);
console.log(resOption2);
JavaScript:
// Create the object which is an array
var output = new objPropertyAndValues;
var TempArray=[]; // blank array
// Lets grab the URL (windows.location.href)
var url_string = window.location.href;
var url = new URL(url_string);
//We now have URL as an object to read from.
//Lets turn the searchParams into a string which we can then split into an Array
var urlParamsString = url.searchParams.toString();
//Now lets split urlParamsString into an array
var AllParamsFound = urlParamsString.split("&");
// Lets read each array item by doing a loop
// We then split the array item value by the "=" sign to split parameter and value
for (i = 0; i < AllParamsFound .length; i++){
TempArray= AllParamsFound [i].split("=");
output.Property[i] = TempArray[0];
output.Value[i] = TempArray[1];
}
console.log(output);
//We allow an object to be created.
function objPropertyAndValues(){
this.Property = [];
this.Value = [];
}
Running Example:
// Create the object which is an array
var output = new objPropertyAndValues;
var TempArray=[]; // blank array
// Lets grab the URL (windows.location.href)
var url_string = "http://www.google.com?myName=Datacure&AnswerID=54379924&Likes=Pizza";
var url = new URL(url_string);
//We now have URL as an object to read from.
//Lets turn the searchParams into a string which we can then split into an Array
var urlParamsString = url.searchParams.toString();
//Now lets split urlParamsString into an array
var AllParamsFound = urlParamsString.split("&");
// Lets read each array item by doing a loop
// We then split the array item value by the "=" sign to split parameter and value
for (i = 0; i < AllParamsFound .length; i++){
TempArray= AllParamsFound [i].split("=");
output.Parameter[i] = TempArray[0];
output.Value[i] = TempArray[1];
}
// Example output
console.log (output.Value[0] + " should get " + output.Value[2] + " for answering question id: " + output.Value[1]);
// View the array
console.log(output);
//We allow an object to be created.
function objPropertyAndValues(){
this.Parameter = [];
this.Value = [];
}

How to extract a REGEX query string result array into a Javascript object [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Use the get paramater of the url in javascript
How can I get query string values in JavaScript?
In Javascript, how can I get the parameters of a URL string (not the current URL)?
like:
www.domain.com/?v=123&p=hello
Can I get "v" and "p" in a JSON object?
Today (2.5 years after this answer) you can safely use Array.forEach. As #ricosrealm suggests, decodeURIComponent was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
hash based routing (#cmfolio)
array parameters (#user2368055)
proper use of decodeURIComponent and non-encoded = (#AndrewF)
non-encoded + (added by me)
For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.

Javascript: save way to read GET without PHP

I know about GET variables and javascript there are many questions, but I do not understand or get them to work.
I have a html formular, and I need to populate a field with the value of the get variable. The url has 2 variables, here an example:
?pid=form.html&id=9869118
This page is a html only, so I cannot use php, but I want to (firstly) alert, the value of id.
I have tried so many different versions of solutions here and from google.
(For example:
http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
Please help me to understand how its done correctly and save! Please note, I have no jquery either.
Here is what I have tried so far. This is inside the <script> tags inside my form.html
var GETDATA = new Array();
var sGet = window.location.search;
if (sGet)
{
sGet = sGet.substr(1);
var sNVPairs = sGet.split("&");
for (var i = 0; i < sNVPairs.length; i++)
{
var sNV = sNVPairs[i].split("=");
var sName = sNV[0];
var sValue = sNV[1];
GETDATA[sName] = sValue;
}
}
if (GETDATA["id"] != undefined) {
document.forms.otayhteytta.id.value = GETDATA["id"];
}
Take a look at this excellent javascript url manipulation library:
http://code.google.com/p/jsuri/
You can do stuff like this:
Getting query param values by name
Returns the first query param value for the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat') // 1
Returns all query param values the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat') // [1, 2, 3]
You can use a pure JavaScript function for that like so:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
And then you can alert the value of 'id' like so:
alert(getParameterByName('id'));
You can check if the parameter exists using a simple 'if' condition:
var id = getParameterByName('id');
if (id != "") {
alert(id);
}
Source: How can I get query string values in JavaScript?
A simple way to get the GET parameters without using a library:
var parameters = []
var parts = location.search.substr(1).split('&')
for(var part in parts) {
var splitted = parts[part].split('=')
parameters[splitted[0]] = splitted[1]
}
Now parameters is an array with the parameter name in the key and the value as the value.
This is a simple solution and may not work for all scenario's.

Parse variables from querystring in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I get query string values?
I have the following querystring:
"active_tab=delivered&active_tab=all&active_tab=delivered&active_tab=outstanding
&active_tab=delivered&active_tab=outstanding&active_tab=all&active_tab=delivered&active_tab=outstanding&title_filter=conformance&title_filter=delivering&title_filter=packaging
&title_filter=delivering&title_filter=all&title_filter=delivering&title_filter=all&title_filter=packaging&title_filter=conformance&title_filter=packaging
&title_filter=delivering&title_filter=packaging&title_filter=ordered"
How would I parse the final title_filter ("ordered") and active_tab ("delivered") from the above querystring? Also, if that querystring variable doesn't exist, have it = ""
var query = {};
var largeString = "active_tab=delivered&active_tab=all&active_tab=delivered&active_tab=outstanding&active_tab=delivered&active_tab=outstanding&active_tab=all&active_tab=delivered&active_tab=outstanding&title_filter=conformance&title_filter=delivering&title_filter=packaging&title_filter=delivering&title_filter=all&title_filter=delivering&title_filter=all&title_filter=packaging&title_filter=conformance&title_filter=packaging&title_filter=delivering&title_filter=packaging&title_filter=ordered";
largeString.split('&').forEach(function(keyValue){
var kvp = p.split('=');
query[kvp[0]]= kvp[1];
});
if you need to support arrays:
largeString.split('&').forEach(function(keyValue){
var kvp = keyValue.split('=');
if(kvp[0] in query){
if(typeof(query[kvp[0]] === 'string')){
query[kvp[0]] = [query[kvp[0]]];
}
query[kvp[0]].push(kvp[1]);
}else{
query[kvp[0]] = kvp[1];
}
});
I modified the querystring to remove duplicates and then I did:
var active_tab = window.location.search.split('active_tab=')[1].split('&')[0]
var title_filter = window.location.search.split('title_filter=')[1].split('&')[0]

How to get "GET" request parameters in JavaScript? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
How to get "GET" variables from request in JavaScript?
Does jQuery or YUI! have this feature built-in?
Update June 2021:
Today's browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).
Original:
All data is available under
window.location.search
you have to parse the string, eg.
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
just call the function with GET variable name as parameter, eg.
get('foo');
this function will return the variables value or undefined if variable has no value or doesn't exist
You could use jquery.url I did like this:
var xyz = jQuery.url.param("param_in_url");
Check the source code
Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser
try the below code, it will help you get the GET parameters from url .
for more details.
var url_string = window.location.href; // www.test.com?filename=test
var url = new URL(url_string);
var paramValue = url.searchParams.get("filename");
alert(paramValue)
Just to put my two cents in, if you wanted an object containing all the requests
function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};
var QueryString = getRequests();
//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3
Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.
function Request(name){
return QueryString[name.toLowerCase()];
}
Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:
var queryString = location.search
let params = new URLSearchParams(queryString)
// example of retrieving 'id' parameter
let id = parseInt(params.get("id"))
console.log(id)
You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.
A map-reduce solution:
var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});
Usage:
For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.
If you already use jquery there is a jquery plugin that handles this:
http://plugins.jquery.com/project/query-object
The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.
function getUrlParameter(name) {
var urlOld = window.location.href.split('?');
urlOld[1] = urlOld[1] || '';
var urlBase = urlOld[0];
var urlQuery = urlOld[1].split('#');
urlQuery[1] = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor = urlQuery[1] || '';
var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName = parameterString.split('=')[0];
paramValue = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}
Works for me in
url: http://localhost:8080/#/?access_token=111
function get(name){
const parts = window.location.href.split('?');
if (parts.length > 1) {
name = encodeURIComponent(name);
const params = parts[1].split('&');
const found = params.filter(el => (el.split('=')[0] === name) && el);
if (found.length) return decodeURIComponent(found[0].split('=')[1]);
}
}

Categories