Split string in JavaScript and detect line break

前端 未结 7 1170
情书的邮戳
情书的邮戳 2020-12-24 04:55

I have a small function I found that takes a string from a textarea and then puts it into a canvas element and wraps the text when the line gets to

7条回答
  •  一向
    一向 (楼主)
    2020-12-24 05:29

    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;
        }
    

提交回复
热议问题