0

I have an string that I would like to turn into an array, taking every 3 characters in the string as an item in that array. For example"

var theString = "hello there!"

// the resulting array will look like this
["hel", "lo ", "the", "re!"]
shrewdbeans
  • 11,971
  • 23
  • 69
  • 115

1 Answers1

1

You could try something like this:

var theString = "hello there!";
var arr = [];

for (var i = 0; i < theString.length; i+=3) {
  arr.push(theString.substring(i, i+3));
}
alex
  • 6,818
  • 9
  • 52
  • 103
  • I tried this in the console, `arr` comes back as: `["hel", undefined × 2, "lo ", undefined × 2, "the", undefined × 2, "re!"]` – shrewdbeans Jan 13 '15 at 11:24
  • Ah right - that's because only arr[0], arr[3], arr[6] (etc.) exist due to arr[i] incrementing by three after every iteration of the for loop. `Array.push()` can also be used, and it will add values to the end of `arr[]`. I updated my answer to reflect this. – alex Jan 13 '15 at 14:30