1

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.

1
  • 3
    Does it have to be RegEx? Commented Nov 15, 2013 at 17:33

2 Answers 2

5

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, '[$&]') +']');
Sign up to request clarification or add additional context in comments.

3 Comments

a 2 dimensional array is needed
@ArunPJohny Yeah, I accidentally used filter instead of map.
This method will truncate the last value if the string contains an odd number of comma-separated values.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.