Reputation: 1463
I have the following javascript string varaible:
var a = "1870|A00,1871|A01";
I want to separate the above string into the below strings:
var a1 = 1870,1871
var a2 = A00,A01
Any hints on this?
Upvotes: 1
Views: 1538
Reputation: 14766
To split a string the Javascript split method can be used. Split accepts as a parameter the delimiter you want to split on, in your case the comma and the pipe. It returns an array of objects found before and after the delimiter (which ends up being an array sized one larger than the number of times the delimiter appears).
To add an object to an array on the fly for building up your a1 and a2, use push. Push adds an object to the end of an array.
To get a string from your two arrays with commas separating each, use join. Join takes an array and returns a string with whatever your argument is separating each entry.
var a1 = [];
var a2 = [];
var firstGrouping = a.split(",");
var firstGroupingLength = firstGrouping.length;
for(var i = 0; i < firstGroupingLength; i++) {
var secondGrouping = firstGrouping[i].split("|");
a1.push(secondGrouping[0]);
a2.push(secondGrouping[1]);
}
var a1String = a1.join(',');
var a2String = a2.join(',');
To generalize the code above to allow for more items grouped around the pipe (such as an input string var a = "1870|Z26|A00,1871|Z25|A01"
), instead of a1 and a2 consider an array of arrays that is constructed dynamically.
Upvotes: 2
Reputation: 407
This can be done fairly easily using a regular expression replace.
var a1 = a.replace(/\|A[0-9]+/,"");
var a2 = a.replace(/[0-9]+\|/,"");
I have not tried the code but it should work.
Upvotes: 0
Reputation: 339786
var a = "1870|A00,1871|A01";
var b = a.split(','); // split on the commas
var a1 = [], a2 = []; // temporary arrays
// foreach of the substrings
for (var i = 0; i < b.length; ++i) {
var c = b[i].split('|'); // split on the pipe char
a1.push(c[0]); // and store the
a2.push(c[1]); // two elements
}
a1 = a1.join(','); // and reconstruct the
a2 = a2.join(','); // two strings
Upvotes: 1
Reputation: 123791
var a = "1870|A00,1871|A01";
var a1 = a.match(/\d+(?=\|)/g);
var a2 = a.match(/\w\d+(?=,|$)/g);
// a1
// 1870,1871
// a2
// A00,A01
Upvotes: 4
Reputation: 86872
var a = "1870|A00,1871|A01"
var splita = a.split(",");
splita[0] = splita[0].split("|");
splita[1] = splita[1].split("|");
var a1 = [splita[0][0], splita[1][0]];
var a2 = [splita[0][1], splita[1][1]];
Upvotes: 0
Reputation: 15616
Try Google next time, use the .split() - http://www.w3schools.com/jsref/jsref_split.asp method. To split your string into an array like so.
var a="1870|A00,1871|A01";
var parts = a.split(",");
Upvotes: 0