Parse string to array - javascript

Is there by any chance a built-in javascript function that parses:
var string = '[2,1,-4]';
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
to
var array = [2,1,-4];
var multiArray = [[-3,2,-1],[2,-3,2],[1,-1,3]];
or do I have to write a custom function for this?

Assuming your correct your multiString to the correct format
(ie. '[[-3,2,-1],[2,-3,2],[1,-1,3]]')
Then yes.
array = JSON.parse(string);
multiArray = JSON.parse(multiString);

For completeness, you can use eval:
var s = '[1,2,3]';
var a = eval(s);
however if the string is valid JSON, then as Niet suggested, JSON.parse is a much better solution.

If you want to do this on your own, it can be done using substring and split. A possible solution could look like this:
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
var string = '[2,1,-4]';
function parse(input) {
var s = input;
// remove leading [ and trailing ] if present
if (input[0] == "[") {
s = input.substring(0, input.length);
}
if (input[input.length] == "]") {
s = s.substring(input.length-1, 1);
}
// create an arrray, splitting on every ,
var items = s.split(",");
return items;
}
// items is now an array holding 2,-1,4
var items = parse(string);
You can then split the bigger string into smaller chunks and apply the function to each part using array.map:
function parseAOfA(input) {
var s = input.substring(0, input.length).substring(input.length-1, 1);
s = s.substring(0, s.length).substring(s.length-1, 1);
s = s.split("][");
var items = s.map(parse);
return items;
}
var items = parseAOfA(multiString);

Related

Need hint for string method

I'm making a prep course for a bootcamp - yes, n00b over here! - and I'm stuck in this particular exercise about String Methods
I need to manipulate this original string 'supercalifragilisticexpialidocious' and obtain the following version: docious-ali-expi-istic-fragil-cali-rupus
I've tried this:
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(9,5);
var newWord7 = bigWord.slice(5,9);
var newWord8 = bigWord.charAt(4);
var newWord9 = bigWord.slice(1,2);
var newWord10 = bigWord.charAt(2);
var newWord11 = bigWord.slice(32);
console.log(newWord1,newWord2,newWord3,newWord4,newWord5,newWord6,newWord7,newWord8,newWord9,newWord10,newWord11);
Does anybody have a hint for me? Can someone help me out?
Cheers!
Here is a code snipet that works. It does not answer your question though:
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(5,9);
var newWord7 = bigWord.charAt(4) + bigWord.slice(1,2) + bigWord.charAt(2) + bigWord.slice(32);
console.log([newWord1,newWord2,newWord3,newWord4,newWord5,newWord6,newWord7].join("-"));
The problems are:
you used .slice(9,5) for word 6 which is incorrect, because 9 is behind the 5 and therefore newWord6 did not get the correct result, but "" (empty string)
you did not add up word 7 to a whole, but printed its elements separately
you have to print minus characters in between
either by putting + "-" + between every variables
or by adding up an array like mine and use the join() operator
I would go for some Regexep stuff
const original = 'supercalifragilisticexpialidocious';
const expected = 'docious-ali-expi-istic-fragil-cali-repus';
// the most common way to reverse a string is to explode it to an array and use the standard reverse method and then joining it back again as a string
function reverseString(str) {
return str.split("").reverse().join("");
}
// the replacer method do the job of concataining words joining them by dash and call the reverse method for the last matched word.
function replacer(match, p1, p2, p3, p4, p5, p6, p7, offset, string) {
return [p7, p6, p5, p4, p3, p2, reverseString(p1)].join('-');
}
// pick the words by block of letters
const actual = original.replace(/(\w{5})(\w{4})(\w{6})(\w{5})(\w{4})(\w{3})(\w{7})/, replacer);
console.log(expected === actual);
I tried to make a simple example for you while keeping things somewhat dynamic so you can learn.
Assuming you want the words sliced from the end of the string to the start of it and then combined back together in reverse with a - then all you need to 'hardcode' is the length of each word to slice (from the start to the end) and then loop through that and slice out your words. So if you want to turn supercalifragilisticexpialidocious into docious-ali-expi-istic-fragil-cali-super you can do this:
var bigWord = 'supercalifragilisticexpialidocious';
var slices = [5, 4, 6, 5, 4, 3, 7];
var words = [], lastSlice = 0;
slices.forEach(slice => {
words.push(bigWord.slice(lastSlice, lastSlice + slice))
lastSlice += slice;
});
// Reverse the sliced words and join them back together with -
words = words.reverse().join('-');
console.log(words); // outputs docious-ali-expi-istic-fragil-cali-super
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(5,9);
var newWord7 = bigWord.charAt(4) + bigWord.slice(1,2) + bigWord.charAt(2) + bigWord.slice(32);
var newBigWord =(newWord1+'-'+newWord2+'-'+newWord3+'-'+newWord4+'-'+newWord5+'-'+newWord6+'-'+newWord7);
console.log(newBigWord);

each & for loop mixed up my array order

I've created an associative array for index spaces inside a sentence for example:
sentence: hello how are you? (spaces between the word 'hello' to 'how')
so my array looks like this:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
but when I use 'for' loop its show me (using alert) the indexes 0,1,2,3 first and after them the sub-indexes, its mixed up my array order, any idea?
here my code:
function words_indexer(user_content)
{
var words_array = user_content.split(" ");
var indexed_words = {};
var word_counter = 0
var last_word_counter = 0
$.each(user_content, function(word_key,word_value){
if(word_value === ''){
var indexed_key = last_word_counter + '_' + word_key;
indexed_words[indexed_key] = word_value;
}else{
var indexed_key = word_counter;
indexed_words[indexed_key] = word_value;
last_word_counter = word_counter;
word_counter++;
}
});
for (var key in indexed_words) {
alert(key + ' ' + indexed_words[key]);
}
}
If your array index needs an extra level of structure then it may be better to just create a nested array instead:
indexed_words[0] = hello
indexed_words[0][1] = space
indexed_words[0][2] = space
indexed_words[0][3] = space
indexed_words[0][4] = space
indexed_words[0][5] = space
indexed_words[0][6] = space
indexed_words[0][7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
I believe adding an underscore to your array key may actually cause Javascript to consider it as being a string which would bump your numeric keys up above it.
You can't use non-numeric indexes for arrays in javascript (a_b is not considered numeric). For this you probably should use an object. And then loop through it like this:
for(var word_key in indexed_words) {
if(!indexed_words.hasOwnProperty(word_key)) continue;
var word_value = indexed_words[word_key];
// Your code
}

How to split and change to different format in javascript

I am new for javascript, I have a one long string i want to split after 3rd commas and change diffferent format. If you are not understand my issues. Please see below example
My string:
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
I want output like this:(Each item should be in next line)
Idly(3 Pcs) - 10 = 200
Ghee Podi Idly - 10 = 300
How to change like this using JavaScript?
Just copy and paste it. Function is more dynamic.
Example Data
var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
Function
function writeData(data){
data = data.split(',');
var tempLine='';
for(var i=0; i<data.length/3; i++) {
tempLine += data[i*3+1] + ' - ' + data[i*3] + ' = ' + data[i*3+2] + '\n';
}
alert(tempLine);
return tempLine;
}
Usage
writeData(testData);
Use split method to transform the string in a array and chunk from lodash or underscore to separate the array in parts of 3.
// A custom chunk method from here -> http://stackoverflow.com/questions/8495687/split-array-into-chunks
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
});
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var arr = test.split(',');
var arr = arr.chunk_inefficient(3);
arr.forEach(function (item) {
console.log(item[1]+' - '+item[0]+' = '+item[2]);
});
You can use split to split the string on every comma. The next step is to iterate over the elements, put the current element into a buffer and flush the buffer if it's size is three. So it's something like:
var tokens = test.split(",");
var buffer = [];
for (var i = 0; i < tokens.length; i++) {
buffer.push(tokens[i]);
if (buffer.length==3) {
// process buffer here
buffer = [];
}
}
If you have fix this string you can use it otherwise validate string.
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var test2= test.split(",");
var temp_Str= test2[1]+' - '+test2[0]+' = '+test2[2]+'\n';
temp_Str+= test2[4]+'-'+test2[3]+' = '+test2[5];
alert(temp_Str);

Extracting specific information from an array

I have data two sets of data as follows:
"One.Two.Three.Four"
"One.Two.Three.1.Four"
The first three parts are fixed and the remaining can extend to as many as possible.
I am trying to build an object where I want to split and combine whatever is present after three into an object.
var split = samplestr.split('.');
var finalarray = [];
if(split.length>4)
{
finalarray[0] = split[0];
finalarray[1] = split[1];
finalarray[2] = split[2];
finalarray[3] = split[3]+"."split[4];
}
I need to generalise this such that even if the string is of the form
"One.Two.Three.1.2.3.Four"
finalarray[3] = 1.2.3.Four;
Any hints on generalising this?
With Array#shift and Array#join.
var split = samplestr.split('.');
var finalarray = [];
if(split.length > 4) {
finalarray[0] = split.shift();
finalarray[1] = split.shift();
finalarray[2] = split.shift();
finalarray[3] = split.join(".");
}
simply replace
finalarray[3] = split[3]+"."split[4];
with
finalarray[3] = split.slice(3).join(".");
Split the string, slice the first part and append the join'ed second part:
console.info=function(x){document.write('<pre>'+JSON.stringify(x,0,3)+'</pre>')}
//--
var str = "One.Two.Three.Four.More.Stuff";
var s = str.split('.');
var result = s.slice(0, 3).concat(s.slice(3).join('.'));
console.info(result);

Find text between two characters and for each, do something

I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.

Categories