Reputation: 11755
I have a string with a list of items. The items in the list contain strings which represent numbers.
var list = '"One","Two","3,842","3,549","3,653","4,443","3,994","3,935"'
I tried splitting like so:
list.split(',')
// result: [""One"", ""Two"", ""3", "842"", ""3", "549"", ""3", "653"", ""4", "443"", ""3", "994"", ""3", "935""]
Which is not what I intended.
I would like:
["One","Two","3,842","3,549","3,653","4,443","3,994","3,935"]
// or even better:
["One", "Two", 3842, 3549, 3653, 4443, 3994, 3935]
How do I correctly split this string into an array like above?
Upvotes: 2
Views: 70
Reputation: 11137
You just need
list.split(',"').map(function(e) {
return e.replace(/"|,/g, '');
});
to make sure ,
is always followed by a "
, and then remove any extra "
or ,
then the result will be:
["One", "Two", "3842", "3549", "3653", "4443", "3994", "3935"]
Upvotes: 4
Reputation: 14423
Why not do a match of the elements inside the quotes?
var list = '"One","Two","3,842","3,549","3,653","4,443","3,994","3,935"';
var elems = list.match(/"[^"]*"/g);
A lengthier version with a capture group (this one doesn't have the extra double quotes):
var list = '"One","Two","3,842","3,549","3,653","4,443","3,994","3,935"',
re = /"([^"]*)"/g,
arr = [],
result;
while(result = re.exec(list)){
arr.push(result[1]);
}
Upvotes: 2