Split string in JavaScript and detect line break

JavascriptStringCanvasSplitLine Breaks

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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!

Solution 2 - Javascript

Split string in JavaScript

var array = str.match(/[^\r\n]+/g);

OR

var array = str.split(/\r?\n/);

Performance

Solution 3 - Javascript

In case you need to split a string from your JSON, the string has the \n special character replaced with \\n.

Split string by newline:

Result.split('\n');

Split string received in JSON, where special character \n was replaced with \\n during JSON.stringify(in javascript) or json.json_encode(in PHP). So, if you have your string in a AJAX response, it was processed for transportation. and if it is not decoded, it will sill have the \n replaced with \\n** and you need to use:

Result.split('\\n');

Note that the debugger tools from your browser might not show this aspect as you was expecting, but you can see that splitting by \\n resulted in 2 entries as I need in my case: enter image description here

Solution 4 - Javascript

You can use the split() function to break input on the basis of line break.

yourString.split("\n")

Solution 5 - Javascript

You should try detect the first line.

Then the:

if(n == 0){
  line = words[n]+"\n";
}

I'm not sure, but maybe it helps.

Solution 6 - Javascript

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

Solution 7 - Javascript

Here's the final code I [OP] used. Probably not best practice, but it worked.

function wrapText(context, text, x, y, maxWidth, lineHeight) {
 
    var breaks = text.split('\n');
    var newLines = "";
    for(var i = 0; i < breaks.length; i ++){
      newLines = newLines + breaks[i] + ' breakLine ';
    }
    
    var words = newLines.split(' ');
    var line = '';
    console.log(words);
    for(var n = 0; n < words.length; n++) {
      if(words[n] != 'breakLine'){
        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;
        }
      }else{
          context.fillText(line, x, y);
          line = '';
          y += lineHeight;
      }
    }
    context.fillText(line, x, y);
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDustin SilkView Question on Stackoverflow
Solution 1 - JavascriptJean-PaulView Answer on Stackoverflow
Solution 2 - JavascriptTính Ngô QuangView Answer on Stackoverflow
Solution 3 - JavascriptprofimedicaView Answer on Stackoverflow
Solution 4 - Javascriptsau0409View Answer on Stackoverflow
Solution 5 - JavascriptNetzachView Answer on Stackoverflow
Solution 6 - JavascriptmartinView Answer on Stackoverflow
Solution 7 - JavascriptjacksondcView Answer on Stackoverflow