Dustin Silk Dustin Silk - 1 month ago 15
Javascript Question

JavaScript split string, detect line break

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 too long. But it doesn't detect line breaks. This is what it's doing and what it should do:

Input:

Hello

This is dummy text that could be inside the text area.
It will then get put into the canvas.


Wrong output:

Hello this is dummy text
that could be inside the
text area. It will then
get put into the canvas.


What it should output:

Hello

This is dummy text that
could be inside the text
area. It will then get
put into the canvas.


This is the function I'm using:

function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';

for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
context.fillText(line, x, y);
}


Is it possible to achieve what I'm trying to get? Or is there a way to simply move the text area as is into the canvas?

Answer

Use the following:

var enteredText = document.getElementById("textArea").value;
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
alert('Number of breaks: ' + numberOfLineBreaks);

DEMO

Now what I did was to split the string first using linebreaks, and then split it again like you did before. Note: you can also use jQuery combined with regex for this:

var splitted = $('#textArea').val().split("\n");               // will split on line breaks

Hope that helps you out!

(Note: this question was already asked once here).