This is what I used to print text to a canvas. The input is not coming from a textarea
, but from input
and I'm only splitting by space. Definitely not perfect, but works for my case. It returns the lines in an array:
splitTextToLines: function (text) {
var idealSplit = 7,
maxSplit = 20,
lineCounter = 0,
lineIndex = 0,
lines = [""],
ch, i;
for (i = 0; i < text.length; i++) {
ch = text[i];
if ((lineCounter >= idealSplit && ch === " ") || lineCounter >= maxSplit) {
ch = "";
lineCounter = -1;
lineIndex++;
lines.push("");
}
lines[lineIndex] += ch;
lineCounter++;
}
return lines;
}