How to get multiple named querystring values in jQuery/Javascript? - javascript

I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.

Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/

You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!

This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]

Related

Add items to local storage across multiple pages

There are two files. The first:
<div class="someclass">text1</div>
<div class="someclass">text2</div>
<script>
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
</script>
That gives: ["text1","text2"]
The second (files are identical except inner text in first two lines):
<div class="someclass">text3</div>
<div class="someclass">text4</div>
<script>
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
</script>
That gives: ["text3","text4"]
I would like the second file to give ["text1","text2","text3","text4"], or maybe ["text3","text4","text1","text2"].
How can I do that?
You need to retrieve the previously-stored data (if any), and append to that array. Something like:
var foostr = localStorage.foobar || "[]";
arr = JSON.parse(foostr);
var foo = document.getElementsByClassName("someclass");
Array.prototype.forEach.call(foo, function(elem) {
arr.push(elem.innerHTML);
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
So you need to see if there is anything and concatenate it to the array.
if (localStorage.foobar) {
var prev = JSON.parse(localStorage.foobar);
arr = arr.concat(prev);
}
localStorage.foobar = JSON.stringify(arr);
You can concat the both arrays after retrieving localStorage's contents first, using JSON.parse():
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(JSON.parse(localStorage.foobar).concat(arr));
console.log(localStorage.foobar);

How to push a value in an array

i want to know how can i store data in an array like that in order to do it with push function.
here is the code
var data_array = [];
and data look like that
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
any help to change this way of inserting and use push function .
May be this will help,
You can loop through all the keys of the object and push each one into the array
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var keysArray = Object.keys(my_data);
keysArray.forEach(function(key, index) {
data_array.push({ key : my_data[key]});
});
console.log(data_array);
Try this (wrap data in curly braces):
data_array.push( {"2011":{"name":"Team Leaders","total":93,"drilldown":"true"} })
I don't know Exactly what do you want. Anyway, I think that It works for you.
var personInfo = new Object();
var my_data = new Object();
personInfo.name = 'Team Leaders';
personInfo.total = 93;
personInfo.drilldown = 'true';
my_data.person1 = personInfo;
my_data.person2 = personInfo;
// confirm
var jsonType = JSON.stringify(my_data);
console.log(jsonType);
I think this is what you need
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var data_keys= Object.keys(my_data);
data_keys.forEach(function(key, index) {
var obj = {};
obj[key] = my_data[key];
data_array.push(obj);
});

How to build 2 dimensional array from a string of options for a select tag in Javascript?

In Javascript, I have a string of options for a select tag. This is my string:
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>';
In Javascript, I want to convert it to a 2-dimensional Array where 1st dimension will store the id and 2nd dimension will store the text of an option.
How can I do that? I am looking for Javascript solution; I am open to 3rd party solutions also like jQuery.
You can do it by converting the string into DOM options, then iterating over them, so:
var s = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>'
function optionsAsArray(s) {
var sel = document.createElement('select');
var result = [[],[]];
sel.innerHTML = s;
Array.prototype.forEach.call(sel.options, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
console.log(JSON.stringify(optionsAsArray(s))); // [["","1","2"],["","Self Service","Administrator"]]
You can also do it by parsing the string, but that may be more work.
Edit
You can also use the new DOMParser, but fairly recent browsers are required for support:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
var result = [[],[]];
Array.prototype.forEach.call(opts, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
The above creates an array of:
[[id0, id1, id2, ...], [text0, text1, text2, ...]]
if you want pairs like:
[[id0, text0], [id1, text1], ...]
Then the above can be:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
return Array.prototype.map.call(opts, function(opt) {
return [opt.id, opt.text];
});
}
// [["",""],["1","Self Service"],["2","Administrator"]]
which can be reduced to:
function optionsAsArray(s) {
return Array.prototype.map.call(new DOMParser().parseFromString(s, "text/html").querySelectorAll('option'), function(opt) {
return [opt.id, opt.text];
});
}
I have used jQuery for the solutions below.
If you want the array to be made from DOM then you can do this
<select id="selectopt"><option id="">Select</option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option></select>
var arr = [];
console.log('====array 1===');
$('select option').each(function(){
var id = $(this).attr('id');
var value = $(this).text();
arr.push([id, value]);
console.log(arr);
});
If you need it to be made using the string then use $.parseHTML for converting the string to DOM nodes.
var arr2 = [];
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option>';
var options = $.parseHTML(myOptionsString);
console.log('====array 2===');
for (var i=0; i< options.length; i++){
var id1 = options[i].id;
var value1 = options[i].value;
arr2.push([id1, value1]);
console.log(arr2);
}
Fiddle Demo

How to get the parameter value from URL in Jquery?

Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});
jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];
This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}
I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

jQuery convert data-* attributes to lower camel case properties

I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this?
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
if (data['class-name']) {
options.className = data['class-name'];
}
if (data['align-x']) {
options.alignX = data['align-x'];
}
if (data['align-y']) {
options.alignY = data['align-y'];
}
if (data['offset-y']) {
options.offsetY = data['offset-y'];
}
if (data['offset-x']) {
options.offsetX = data['offset-x'];
}
$this.poshytip(options);
});
I would use a for..in loop to read the data-* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... Source code reference.
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[keys] = data[keys];
}
// For older versions of jQuery you can use $.camelCase function
for (var keys in data) {
options[$.camelCase(keys)] = data[keys];
}
});
DEMO
for jQuery 1.4.4,
$('.poshytip-trigger').each(function(index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[camelCase(keys)] = data[keys];
}
});
//copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase
function camelCase(str) {
return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) {
return (letter + "").toUpperCase();
});
}
DEMO for 1.4.4
Something like this - It does convert offset-x to offsetX:
http://jsfiddle.net/8C4rZ/1/
HTML:
<p data-test="sdsd" data-test2="4434"></p>​
JavaScript:
$(document).ready(function() {
var options = {};
for (var key in $("p").data()) {
options[key] = $("p").data(key);
}
console.log(options);
});​
But I think Daniel's approach is better, since he explicitly controls which attributes gets set. This will take all data- attributes.
var names = ["className", "alignY", ...];
$(names).each(function(ind, name){
var dataName = name.replace(/[A-Z]/, function(letter){
return letter.toLowerCase();
});
if(data[dataName]){
options[name] = data[dataName];
}
});
Does this work? Unlike the other answers, this piece of code both convert only explicitly set attributes and keeps the options-object attribute name camelCase.
Try using a for in loop.
var array = ['class-name', 'align-x', 'align-y', 'offset-y', 'offset-x'];
for (x in array) {
if(data[array[x]]) {
options[array[x]] = data[array[x]];
}
}
Update: In response to the OP's clarification, he could write something like this:
var Pair = function(hyphenated, camcelCased) {
this.hyphenated = hyphenated;
this.camelCased = camelCased;
}
var array = [
new Pair('class-name', 'ClassName'),
new Pair('align-x', 'alignX'),
new Pair('align-y', 'alignY'),
new Pair('offset-x', 'offsetX'),
new Pair('offset-y', 'offsetY')];
var i, optionNameHyphenated, optionNameCamelCased;
for(i = 0; i < array.length; i++) {
optionNameHyphenated = array[i]['hyphenated'];
optionNameCamelCased = array[i]['camelCased'];
if (data[optionNameHyphenated]);
options[optionNameCamelCased] = data[optionNameHyphenated];
}

Categories

Resources