Javascript - Split dynamic string getting values inside brackets - javascript

I have this as data input (it's dynamic so it can be 1 up to 5 brackets in the same string)
data["optionBase"] = {} //declaration
data["optionBase"]["option"] = {} //declaration
data["optionBase"]["option"][value] = {} //declaration
data["optionBase"]["option"][value]["detail"] = somethingHere
Each line comes as a string, not as an array or any other type of javascript object.
How can i get an array out of that string containing something like this:
Line 1:
result[0] = "optionBase"
Line 2:
result[0] = "optionBase"
result[1] = "option"
Line 3:
result[0] = "optionBase"
result[1] = "option"
result[2] = value
Line 4:
result[0] = "optionBase"
result[1] = "option"
result[2] = value
result[3] = "detail"

var s1 = 'data["optionBase"] = {} //declaration';
var s2 = 'data["optionBase"]["option"] = {} //declaration';
var s3 = 'data["optionBase"]["option"][value] = {} //declaration';
var s4 = 'data["optionBase"]["option"][value]["detail"] = somethingHere';
var a = [s1, s2, s3, s4];
var regex = /data\[([^\]]+)\](?:\[([^\]]+)\])?(?:\[([^\]]+)\])?(?:\[([^\]]+)\])?/;
for(var i = 0; i < 4; i++)
{
var result = a[i].match(regex);
//result[0] contains the whole matched string
for(var j = 0; j < 5; j++)
console.log(result[j]);
}
If you want to make it dynamic, you can extract the string and split around ][
var s = 'data["optionBase"]["option"][value]["detail"] = somethingHere';
var m = s.match(/data((?:\[[^\]]+\])+)/);
var substr = m[1].substring(1, m[1].length - 1);
var array = substr.split("][");
console.log(array);

Related

pushing array of string with variables to an array inside a loop

Could someone help me on below code? How do I push an array with variables?
function theBeatlesPlay(musicians, instruments) {
var array = []
var i;
var m = ms[i];
var it = its[i];
var string = "`${m}` plays `${it}`";
for (i = 0; i < 4; i++) {
array.push(string)
}
return array
}
Thanks a lot in advance!
Most of what you did should be placed inside the for loop. Like this:
function theBeatlesPlay(musicians, instruments){
var array = [];
for(var i=0; i<musicians.length; i++){
var m = musicians[i];
var it = instruments[i];
var string = `${m} plays ${it}`;
array.push(string);
}
return array;
}
Also note the syntax for the template literal: the whole string is delimited by backticks, and you should not have those double quotes.
Instead of iteration to 4, use the actual length of the array.
function theBeatlesPlay(musicians, instruments){
var array = []
var i;
for(i=0; i<4; i++){
var m = ms[i];
var it = its[i];
var string = "`${m}` plays `${it}`";
array.push(string)
}
return array
}
yes It is pseudo-code and It's actually something like this;
var ms = ["a a", "b b", "c c"];
var its = ["d d", "e e", "f f"];
function funct(ms, its){
var array = []
var i =0;
for(i=0; i<4; i++){
var m = ms[i];
var it = its[i];
var string = "${m} plays ${it}";
array.push(string)
}
return array
}

How to get characters from second last index using indexof in javaScript?

var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = absoluteURL.lastIndexOf('/');
var result = absoluteURL.substring(n + 1);
//alert(result);
console.log(result);
Here I get the result like 'vikas-kohli' as I am using lastIndexOf.
Now if someone wants to get characters from second last index, or it may be 3rd last index, then how can I get this?
I hope I am able to explain my question well
Insteadof using lastIndexOf('/') use string split('/') method.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var splittedStr = absoluteURL.split('/');
console.log(splittedStr);
Then get the required element from an array.
var res = splittedStr[splittedStr.length-n]; // n: 1,2,3..
cosnole.log(res);
DEMO
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var splittedStr = absoluteURL.split('/');
console.log(splittedStr[splittedStr.length-2]);
Sth like this?
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = 2 //second last
var arr = absoluteURL.split('/')
console.log(arr[arr.length-n])
Just split your URL with /:
var absoluteUrl = "http://stackoverflow.com/users/6262169/vikas-kohli";window.location.pathname;
var splitedUrl = absoluteUrl .split('/');
console.log(splitedUrl);
Then get the element you want in the array.
IndexOf or something like that may not what you need. You can use split instead.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli";
var partNo = 3;
var parts = absoluteURL.split('/');
alert(parts[parts.length - partNo]);
A simple for loop would do the trick.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = absoluteURL.indexOf('/');
absoluteURL = absoluteURL.substring(n+2); // Becasue there are two / first
for(i = 0; i < x ; i++) // x should be such that if it is 1, then only the last string will come, if 2, then the last two strings
{
n = absoluteURL.indexOf('/');
absoluteURL = absoluteURL.substring(n+1);
}
You can use .split() on the window.location.pathname:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
arr.forEach(function(item){
console.log(item);
});
With specific indexes:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
console.log('last::::',arr[arr.length-1]);
console.log('second last::::', arr[arr.length-2]);
Or subsequent pop() can give you last item of array:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
console.log(JSON.stringify(arr, 0, 0), '<---last::::popped-->',arr.pop());
console.log(JSON.stringify(arr, 0, 0), '<-----second last::::popped--->', arr.pop());
We can add a function to do that ourselves.
Add below code snippet:
String.prototype.nIndexOf = function (char, index) {
if (index >= this.split(char).length)
return -1;
else
return this.split(char, index).join(char).length;
}
Then you can use this as following:
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n1 = absoluteURL.nIndexOf('/', 4);
var n2 = absoluteURL.nIndexOf('/', 5);
var result = absoluteURL.substring(n1 + 1, n2);
alert(result);
Hi if u can get nth Index from user u can use this
var nthIndex = 2;
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
for (i = 0; i < nthIndex; i++) {
var n = absoluteURL.lastIndexOf('/');
absoluteURL = absoluteURL.substring(0,n);}
alert(absoluteURL);
Concatenate string from the index you want after splitting it with /
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli";
var n = 2; // set the index from where you want to get characters
var arr = absoluteURL.split('/');
var a = [];
for(var i=n,j=0; i>=0; i--,j++){
a[j] = arr[arr.length-i];
}
console.log(a.join('')); // you can join it with any character
This should work:
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var results = absoluteURL.split('/');
var result = results[results.length-2];
alert(result);

How to separate the string into two categories in jstl?

i have a string as,
String value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
Now i need split the names and those values.
I am unable to identify what to do.
I need to print the values as
Output
---
-----------------------------
' Name ' value '
'------------'--------------'
' Bhavani ' 12 '
' Pallavi ' 13 '
' Charanya ' 14 '
' ' '
----------------------------'
I think it can be done in jstl level..
But can anyone help me how to split that string.
you can use str.replace to create an object:
strvalue = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14"
obj={};
strvalue.replace(/(\w+)<>(\w+)/g,function(_,m1,m2){
obj[m1]=m2
})
console.log(obj)
This should do it:
var str = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
str = str.split('<<>>')
for(var i = 0; i < str.length; i++) {
str[i] = str[i].split('<>');
}
alert(str.join("\n"));
first split with <<>>
than split wiht <>
so you will get array with Bhavani , 12 in two indexes.
its simple to show in any way on view.
Personally, I'd store the key-value pairs in an object:
var myObj = {};
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
var stringArray = string.split('<<>>');
for(i in stringArray){
var key = stringArray[i].split('<>')[0];
var value = stringArray[i].split('<>')[1];
myObj[key] = value;
}
console.log('My object looks like', myObj);
Here is my solution, you'll get an array of objects with a name and value inside each object:
let value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
let splittedString = value.split("<<>>");
let names = [];
splittedString.forEach(function(value) {
let splittedProps = value.split("<>");
names.push({
name: splittedProps[0],
value: splittedProps[1]
});
});
console.log(names);
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var strArr = str.split("<<>>");
var result = {};
for(var i in strArr){
var p = strArr[i].split("<>");
result[p[0]] = p[1];
}
console.log(result);
First split with <<>>
then split string with <>
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}`
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}
alert(string.join("\n"));
`
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var txt = str.split("<<>>").join("|").split("<>").join("|").split("|")
var object=[];
for (var i=0; i<txt.length;i=i+2){
object.push({Name:txt[i],Value:txt[i+1]});
}
console.log(object);

How to zip (compress) a JS array

How would I compress an array?
I am trying to compress an array. I have tried using the lz-string library and converting to/from strings, but I get null/0/[] on decompress.
This is what I'm doing:
var array = [];
for (var i = 0; i < 1024; i++) {
array[array.length] = i % 255;
}
var string = String.fromCharCode.apply(null, array);
var compressed = LZString.compress(string);
var decompressed = LZString.decompress(compressed);
var dearray = [];
for (var i = 0; i < decompressed.length; i++) {
dearray[i] = decompressed.charCodeAt(i);
}
http://jsfiddle.net/ZV5Za/18/
The problem seems to be in the way you're forming the array into a string, and back.
Why not use String.prototype.split() / Array.prototype.join() (Fiddle):
var string = array.join('|');
var dearray = decompressed.split('|');
Or maybe even better: JSON.stringify() / JSON.parse() (Fiddle)
(This actually preserves data types):
var string = JSON.stringify(array);
var dearray = JSON.parse(decompressed);
I don't know how you'd fix the "string -> array" step you are using, though.
Turns out it does work, I just had a typo.
http://jsfiddle.net/ZV5Za/20/
var array = [];
for (var i = 0; i < 1024; i++) {
array[array.length] = i % 255;
}
var string = String.fromCharCode.apply(null, array);
var compressed = LZString.compress(string);
var decompressed = LZString.decompress(compressed);
var dearray = [];
for (var i = 0; i < decompressed.length; i++) {
dearray[i] = decompressed.charCodeAt(i);
}
console.log(array.length, array);
console.log(string.length, string);
console.log(compressed.length, compressed);
console.log(decompressed.length, decompressed);
console.log(dearray.length, dearray);

How to build an array from a string in javascript?

I am trying to grab some values out of a sting that looks like this:
W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748
I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...]
I have this snippet that does the trick, but only for the first value:
var foo = str.substring(str.indexOf(":") + 1);
Use split().
Demo here: http://jsfiddle.net/y9JNU/
var keys = [];
var values = [];
str.split(', ').forEach(function(pair) {
pair = pair.split(':');
keys.push(pair[0]);
values.push(pair[1]);
});
Without forEach() (IE < 9):
var keys = [];
var values = [];
var pairs = str.split(', ');
for (var i = 0, n = pairs.length; i < n; i++) {
var pair = pairs[i].split(':');
keys.push(pair[0]);
values.push(pair[1]);
};
This will give you the keys and values arrays
var keys = str.match(/\w+(?=:)/g),
values = str.match(/[\d.]+(?=,|$)/g);
RegExp visuals
/\w+(?=:)/g
/[\d.]+(?=,|$)/g
And another solution without using regexp
var pairs = str.split(" "),
keys = pairs.map(function(e) { return e.split(":")[0]; }),
values = pairs.map(function(e) { return e.split(":")[1]; });
JSFiddle
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";
var all = str.split(","),
arrayOne = [],
arrayTwo = [];
for (var i = 0; i < all.length; i++) {
arrayOne.push(all[i].split(':')[0]);
arrayTwo.push(all[i].split(':')[1]);
}
parse the string to an array
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";
var tokens = str.split(",");
var values = tokens.map(function (d) {
var i = d.indexOf(":");
return +d.substr(i + 1);
});
var keys = tokens.map(function (d) {
var i = d.indexOf(":");
return d.substr(0, i);
});
console.log(values);
console.log(keys);
http://jsfiddle.net/mjTWX/1/ here is the demo

Categories