0

I have the following array point[] with:

11,133,3032,144,412,44,43,44,444,54,22,44,11,163,480,344

And I am trying to split with a , every 4.

I would like something like:

point[0] = 11,133,3032,144
point[1] = 412,44,43,44
point[2] = 444,54,22,44
point[3] = 11,163,480,344

I alreday tried :

str.split(",", 4); but still have the comma at the end and problem of size.

How can I proceed?

Thanks!

1
  • Is it an array? Because you're using String.split.... Commented Oct 24, 2014 at 12:55

2 Answers 2

2

You can do this by splice-ing the array.

var str = "11,133,3032,144,412,44,43,44,444,54,22,44,11,163,480,344";
var arr = str.split(','), result = [];
while(arr.length > 0) {
   result.push(arr.splice(0, 4));
}

If you have an array instead of the string, you can just use the last three lines.

Sign up to request clarification or add additional context in comments.

Comments

0

If you are trying to get sub strings from the string, you can also do it with regular expressions.

str = "11,133,3032,144,412,44,43,44,444,54,22,44,11";
points = [];
while((match = /([0-9]+,){3}[0-9]+/.exec(str)) != null){
    points.push(match[0]);
    str = str.replace(/([0-9]+,){3}[0-9]+,*/, "");
}
if (str!="")            //if last substring has less than 4 elements
    points.push(str);    

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.