what I am trying to do is have a text "box" that has a certain line length in width without cutting any words in half. what I am trying to do at the moment is cut the text into lines of n length, and then I am trying to repair words by knowing when the next space is. this is what I have at the moment but it does not fully work and only repairs some of the words
function TextBox(length,text){
array = [];
test = /[A-Za-z]+/g;
//cutting the text up
for (i= 0;i < Math.ceil(text.length / length); i ++){
array.push(text.slice(i * length,Math.min((i + 1) * length,text.length)));
}
//in case it ruins the lines the first time round
for (z = 0; z < 3; z++){
//reformatting the code
for (i = 0; i < array.length - 1; i ++){
if (test.test(array[i][array[i].length - 1])){
array[i] += array[i+1].substr(0,array[i+1].indexOf(' ') + 1);
array[i + 1] = array[i + 1].substr(array[i + 1].indexOf(' ') + 1);
}
}
}
//for debugging
console.log(array);
}
TextBox(5,"i like to eat cheese when I am hungry");
EDIT an example of an input is: "i like to eat cheese when I am hungry" and I want something like: [ "i like", "to eat", "cheese", "when I", "am hungry" ] what I am getting out right now is this: [ 'i like ', 'to ', 'eat c', notice the "c" from cheese 'heese', ' when ', 'I am ', 'hung', 'ry' ] and the "ry" from hungry
with the line length around n (5 in this example) characters long.
I have tried adding and removing the extra for loop but from what I can tell it helps to format it.
if you know what I am doing wrong, or an easier way to do this that would be great.