title: Split string in JavaScript and detect line break
body: <p>I have a small function I found that takes a string from a <code>textarea</code> and then puts it into a <code>canvas</code> 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:</p>
  
  <p>Input:</p>
  
  <pre><code>Hello
  
  This is dummy text that could be inside the text area.
  It will then get put into the canvas.
  </code></pre>
  
  <p>Wrong output:</p>
  
  <pre><code>Hello this is dummy text
  that could be inside the
  text area. It will then
  get put into the canvas.
  </code></pre>
  
  <p>What it should output:</p>
  
  <pre><code>Hello
  
  This is dummy text that
  could be inside the text
  area. It will then get
  put into the canvas.
  </code></pre>
  
  <p>This is the function I'm using:</p>
  
  <pre><code>function wrapText(context, text, x, y, maxWidth, lineHeight) {
      var words = text.split(' ');
      var line = '';
  
      for(var n = 0; n &lt; words.length; n++) {
          var testLine = line + words[n] + ' ';
          var metrics = context.measureText(testLine);
          var testWidth = metrics.width;
          if (testWidth &gt; maxWidth &amp;&amp; n &gt; 0) {
              context.fillText(line, x, y);
              line = words[n] + ' ';
              y += lineHeight;
          }
          else {
              line = testLine;
          }
      }
      context.fillText(line, x, y);
  }
  </code></pre>
  
  <p>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?</p>