How do I separate a comma delimited variable into multiple variables? - javascript

This is probably very elementary, but I'm still learning.
I've imported a record from an XML file and have the result :
"a,b,c,d,e,f,g,h"
I would like to end up with 8 separate variables, one for each comma delimited value.
What is the shortest way to code this using javascript?

if you .split() the list, you'll end up with a single array with 'n' number of elements. Not -exactly- 8 separate variables, but 8 elements that can be accessed individually.
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split( ',' );
alert( myArray[ 4 ] );

use split()
js>s = "a,b,c,d,e,f,g,h"
a,b,c,d,e,f,g,h
js>a = s.split(',')
a,b,c,d,e,f,g,h
js>a[0]
a
js>a[4]
e

Use split().
In your case, xml_string.split(',');

If you have the result as a string, use the split method on it:
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split(",");

Related

Array to Newline String to Array again through HTML

I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem

Dynamic string cutting

Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.

split string into multiple output string

I'm having string like this
String input = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00"
I have tried lot of options by google-ing like indexOf() over load etc but could not get the exact result.
Is that possible I could have multiple output string on the basis of "|"
Expected output
String one = input.substring(0,input.indexOf("|")) = ABCD
String two = opt/kelly/box.txt
String three = DXC
String four = 20-12-2015 11:00:00
How can I do for the remaining ones ?
Any suggestion please how can I get this result using indexOf with substring.
Thanks in Advance !!
It's easy. All you need to do is to use .split:
var input = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00";
input = input.split("|");
console.log(input);
But if you need them in variables like one, two, etc., you might need to use destructuring assignment. You don't need to use .indexOf here.
Using Destructuring assignment
var input = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00";
var [one, two, three, four] = input.split("|");
console.log(one);
console.log(two);
console.log(three);
console.log(four);
First, be aware that JavaScript doesn't allow you to declare your data type as you are doing with:
String input ....
You can only declare the variable (i.e. var input ...)
Barring that, the .split() method (which splits a string based on your delimiter and returns an array of the parts to you) will do it.
Also, if you need to store each array element in its own variable, you can use a destructuring assignment to accomplish that.
// Here's your scenario:
var input = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00";
var one = input.substring(0,input.indexOf("|")) // ABCD
// Do the remaining split on the original string without the already found parts
var [two, three, four] = input.replace(one + "|","").split("|");
console.log(one);
console.log(two);
console.log(three);
console.log(four);
// Here'e a cleaner alternative that uses a destructuring assignment:
var input2 = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00";
var [one2, two2, three2, four2] = input.split("|");
console.log(one2);
console.log(two2);
console.log(three2);
console.log(four2);

Deserialize JSON string into array of list

I've a string
var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";
I need to convert it into an array of list. For example,
alert(my_str[1])
would give an output of 1,15.
I've tried the following:
var myarray = JSON.parse(my_str);
but it throws the error "unexpected token ( in JSON at position 1"
I tried this
var myarray = JSON.parse(my_str);
but it throws error "unexpected token ( in JSON at position 1"
So I changed the structure of my string to:
var my_str="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";
That worked like a charm ;)
The problem is that you are using a strange sintax for delimiting inner objects. It would be appropriate to use "[" and "]" instead of "(" and ")".
Anyway you can easily replace them with javascript and make your structure an array of arrays of strings. Sounds a bit creepy, but this way you can create a licit JSON object and benefit of JS native methods.
var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))
you can now work on my_array object and retrieve couples of numbers using array indexes
my_array[1] ---> 1,15
You have to replace ( by '( and ) by )' ,, then , apply eval :
eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]
This is a pretty naive idea, but does work (without JSON.parse or eval):
var arr = my_str.replace('[(', '').replace(')]', '').split('),(');
//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]
var arr = my_str.split("),(")
arr[0] = arr[0].slice(2);
arr[arr.length-1] = arr[arr.length-1].slice(0,-2)

how can i get the values separated by a comma to a array? using java script

i have this static code that will hide/show some combo box but what if i add more category´s ?well if do add more category´s i have to change the code every time
so what i want to do is have a var that will receive several values separated by comma
and them some how it will separate the values and them it will store the values in a array. and now when the user needs to add more category´s i don't have to edit the code.
but how can i separate the values divided by a comma and then add them to a array?
If I understand your question correctly you'll want to have a look at http://www.w3schools.com/jsref/jsref_split.asp
And use var arr = YOURVARIABLE.split(',');
You can use the String.split() function, e.g:
var s = '1,2,3,4,5,6';
var values = s.split(',');
console.log(values);
For more information see here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
You would use the split() method. http://www.w3schools.com/jsref/jsref_split.asp
var string = '1,2,3,text,123';
var array = string.split(',');
//array = [1, 2, 3, 'text', 123];
Try the following code
var testString = "comma,seperated,list";
var stringArr = testString.split(",");
the split() method will literally split the string by the delimeter passed to it and return an array of values. in this case our array will be
// stringArr = ["comma", "seperated", "list"];

Categories