The System Restart
The System Restart

Reputation: 2881

Javascript String Split

I've a String like following:

var str = '35,35,105,105,130,208,50,250';

I would like to split this string and get like this:

var arr = [[35,35],[105,105],[130,208],[50,250]];

I tried some ways, but none of them give me anything. I tried with looping to find the even comma position and split, but that doesn't seem good to me. Please give me some suggestion on this. I'm looking for RegEx Solution.

Upvotes: 1

Views: 95

Answers (2)

VisioN
VisioN

Reputation: 145398

One possible approach:

'35,35,105,105,130,208,50,250'.match(/\d+,\d+/g).map(function(s) {
    return s.split(',');
});

Another crazy idea in one line:

JSON.parse('['+ '35,35,105,105,130,208,50,250'.replace(/\d+,\d+/g, '[$&]') +']');

Upvotes: 5

nderscore
nderscore

Reputation: 4251

Here's one way to do it.

var values = str.split(','),
    output = [];
while(values.length)
    output.push(values.splice(0,2));

If str contains an odd number of values, the last array in output will contain only one value using this method.

Upvotes: 1

Related Questions