Javascript creating arrays from strings - javascript

I have following code:
var selector="a,b,c/m,n",
property = "width,height/font-size";
I want to group each set of strings (separated by forward slash) to new array.
so I would (basically) end up with this:
var selector_array1 = [a,b,c];
var selector_array2 = [m,n];
----
var property_array1 = [width,height];
var property_array2 = [font-size];
....
so I would end up with 2 for loops (I think), like:
for(outer loop){//for each selector array
for(inner loop){//for each item in selector array apply each property in property array
}
}
Bear in mind it can only have 1 value/property like (so no forward slashes to split):
var selector="a/m",
property = "width/font-size";
or like this:
var selector="a",
property = "width";

You can still use split on the ones with no slashes. Just split once on slashes then split those results on commas.
function extractData(input) {
// Separate by /'s
return input.split('/')
.map(function(str) {
// For each of the new strings, split them on commas
return str.split(',');
});
}
var data = extractData('a,b,c/width,height');
console.log(data[0].toString(), '|', data[1].toString());
data = extractData('a,b,c');
console.log(data[0].toString());
data = extractData('a/width,height');
console.log(data[0].toString(), '|', data[1].toString());
data = extractData('a/width');
console.log(data[0].toString(), '|', data[1].toString());

To do that you need to use the split method of the String prototype:
var selector="a,b,c/m,n",
property = "width,height/font-size";
function splitString(s){
// Split the string with the character /
// And loop through the array
return s.split('/').map(function(stringWithComa){
// Return the result of the string split
return stringWithComa.split(',')
})
}
console.log(splitString(selector));
console.log(splitString(property));
Hope it helps ;) Dont hesitate to ask question ;)

Here is an method using split() and arrays.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var selector="a,b,c/m,n";
var property = "width,height/font-size";
var selector_array1 = new Array();
var selector_array2 = new Array();
var property_array1;
var property_array2;
var selectors = selector.split('/');
var properties = property.split('/');
for(var i = 0; i<selectors.length; i++) {
selectors[i] = selectors[i].split(',');
for(var j = 0; j<selectors[i].length;j++) {
if(i==0)
selector_array1.push(selectors[i][j])
else
selector_array2.push(selectors[i][j])
}
}
alert(selector_array1);
alert(selector_array2);
</script>
</body>
</html>

Related

Get all match values from two comma separated string

I have two comma separated string as follows,
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
I need to create another string based on the above two,
if hiddenString have unmatching value with strB,then without those unmatched values need to create e new string and also avoid duplicates.
simply says, I need to get all the matching values from both strings.
As the example based on my two string, I'm expecting the following:
varFinalHiddenString = 14172,10062,100;
How can I do this using JavaScript and that should work in safari and IE 11 or its earlier versions. Please help me, I'm new to the JS.
You can first split() strings to generate arrays from them. Then filter() the smaller array by checking the index of the current item with indexOf() in other array:
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
var temp1 = hiddenString.split(',');
var temp2 = strB.split(',');
var varFinalHiddenString = temp2.filter(function(s){
return temp1.indexOf(s) > -1;
}).join(',');
console.log(varFinalHiddenString);
Make arrays of the strings, then use the "filter" method. Then convert back to string.
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
var hiddenStringAsArray = hiddenString.split(',');
var strBArray = strB.split(',');
var resultObject = $(strBArray).filter(hiddenStringAsArray);
var resultArray = resultObject.toArray();
var resultString = resultArray.join(',');
console.log(resultString);

How to insert two value in one time to array using JavaScript

I want to insert two values in one array in each loop. I have tried
feature_arr = [];
$form.find( '.variations .value' ).each( function() {
var $radios = $( this ).find( 'input[type=radio]' );
var $checked_radio = $radios.filter(':checked');
var attribute_name = $radios.attr( 'name' );
feature_arr[] = attribute_name1;
feature_arr[] = $checked_radio.val();
});
I want array this form ["1", "Brighton_Black", "2", "Frame_Base", "3", "Matching_upholstery", "6", "Headrest", "7", "Covered"]
But give me error this code
try this
var feature_arr = new Array(); // define the array or you can use feature_arr = []
and inside your condition
feature_arr.push(your_value_1);
feature_arr.push(your_value_2);
for the second part for your question in the comment try this
<html>
<head></head>
<title></title>
<style type="text/css">
</style>
<body>
</body>
<script type="text/javascript">
var thestring = "matching_upholstery";// this is your string
alert(toupper(thestring)); // in here we pass out string to the method/function we wrote that returns the converted output string. to see the result we use an alert here.
//this is the function that convert the first letter to upper and return the final result
function toupper(a)
{
var stringArray = a.split('_');//split your word from '_' character.
var firstword = stringArray[0];//get the first word
var firstwordWithupper = firstword.charAt(0).toUpperCase()+firstword.slice(1);//convert the first letter to upper
var secondword = stringArray[1]; // get the second word
var secondwordWithupper = secondword.charAt(0).toUpperCase()+secondword.slice(1);//convert the first letter of second word to upper
var finalresult = firstwordWithupper +"_"+secondwordWithupper;
return finalresult;
}
</script>
</html>
you can also do like
var a = [].concat(1,2);
in one line. In your case inside the condition you can do like
feature_arr = feature_arr.concat(value1,value2)
or if you receive your multiple data in an array this would result the same
feature_arr = feature_arr.concat([value1,value2])

JavaScript - Find and replace word in array

How would I find a word (in this case a placeholder, e.g _ORGAN_) in an array and replace it with an element's value?
sql = new Array();
$('#system').change(function(){
filter = " topography_index = _ORGAN_";
sql.push(filter);
});
In this case I would want to replace _ORGAN_ with $('#organ_menu').val();
Try this:
// sql array
var sql = ['organ not found', '_ORGAN_ is here'];
var val_to_replace = '_ORGAN_';
var replace_with = 'heart'; // temp value - change it with $('#organ_menu').val()
$.each(sql, function (key, val) {
// search for value and replace it
sql[key] = val.replace(val_to_replace, replace_with);
})
console.log(sql)
JSFiddle: http://jsfiddle.net/d8sZT/
You can simply do by iterating the array and then assign the value to once it find its match.
for (i = 0; i < sql.length; i++) {
if (sql[i] === "_ORGAN_") {
sql[i] = $('#organ_menu').val();
}
}
example fiddle for better understanding.
You can simply iterate over the array and use replace on each element
var organValue = $('#organ_menu').val();
for (var i = 0; i < sql.length; i++) {
sql[i] = sql[i].replace("_ORGAN_", organValue);
}
var regExp = new RegExp(organ, 'g');
$.each(sql, function(index, value) {
sql[index] = value.replace(regExp, 'test');
})
I'd try something like this, using replace:
sql = new Array();
$('#system').change(function(){
filter = " topography_index = _ORGAN_".replace("_ORGAN_", $('#organ_menu').val(), "gi");
sql.push(filter);
});
You can do this:
First find the index of the item:
var index=sql.indexOf("_ORGAN_");
Then insert your new item at that index and remove the first one:
sql.splice(index,1,newitem);
splice

Split string in Javascript with _

I am beginner with javascript.I want to create array as 1,2,3,4,5
But I get o/p as ,1,2,3,4,5
I tried with .split() in javascript but I am not getting the required output.
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = new Array();
temp = string.split("testrating_");
for (a in temp ) {
temp[a] = temp[a];
}
fiddle
You could do it this way:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5",
temp = string.split('testrating_');
temp.shift(); //remove fist item which is empty
console.log(temp); //["1", "2", "3", "4", "5"]
The actual value of temp is ["","1","2","3","4","5"]. This is happening because of .split and the string starting with the delimiter.
If you always know the delimiter will be at the start of the string, you can do this, which removes the first element of the Array:
temp = string.split("testrating_").slice(1);
You can try this...
<!DOCTYPE html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = [];
temp = string.split("testrating_");
var tempNew=[];
for (a in temp ) {
if(temp[a]!==''){
tempNew.push(temp[a]);
}
}
alert(tempNew);
}
</script>
</body>
</html>
JSFiddle
You are getting ,1,2,3,4,5 because there is no character at the beginning of the string before testrating_ by which you are separating.
either you can remove testrating_ from first position like statement below
var str="1testrating_2testrating_3testrating_4testrating_5";
str.split("testrating_")
Or you can remove character from first index after getting result as from array
var str="testrating_1testrating_2testrating_3testrating_4testrating_5";
str.split("testrating_").slice(1);
Do this:
<!DOCTYPE html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = new Array();
temp = string.split("testrating_");
var output = new Array();
for (x = 0; x < temp.length; x++) {
output[x - 1] = temp[x];
}
alert(output);
}
</script>
</body>
</html>
You could always use .splice:
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
temp = string.split("testrating_"); // temp = ["","1","2","3","4","5"]
temp.splice(0,1) // temp = ["1","2","3","4","5"]
What splice does here is goes to the first value in the array (index #0) and removes one value from that point which would be the empty string "".
To give a little more of an explanation, you could remove the empty string and "1" by using splice like so:
temp.splice(0,2) // temp = ["2","3","4","5"]
Keep in mind that splice directly effects the array it's called upon and returns an array of values that were removed. So if you did the following:
values = temp.splice(0,2) // values=["","1"] temp=["2","3","4","5"]
Also, in this example creating a new array in the following fashion temp = new Array(); is redundant since string.split() effectively creates an array and fills it with the values that were splitted. Keep that in mind going forward. Hope this helps and welcome to the world of programming!
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
// Split and remove first entry and return an array
var final = string.split("testrating_").slice(1);
$('#out').text(JSON.stringify(final));
Try this:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = string.split("testrating_").join("").split("").join();
console.log(temp);
Can also be done like this:
var temp = string.replace(/testrating_/g,"").split("").join();
or just:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = string.match(/[\d]/g); //your regex here
console.log(temp);
Not sure about the performance though.

How to extract values from a string in javascript?

I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.

Categories