javascriptstringcanvassplitline-breaks

Split string in JavaScript and 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?


Solution

  • Using .split():

    var str = `your text
               that spans
               multiple lines`
    
    // Split the string on \n or \r characters
    var separateLines = str.split(/\r?\n|\r|\n/g);
    
    alert("Total number of separate lines is: " + separateLines.length);

    Or using .match() instead:

    var str = `your text
               that spans
               multiple lines`
    
    // Split the string on \n or \r characters
    var separateLines = str.match(/[^\r\n]+/g);
     
    alert("Total number of separate lines is: " + separateLines.length);