title: Javascript strings wrap
body: <p>I'm trying to find a solution for the following test:
  <em>you should be able to wrap lines at a given number of columns, without breaking words</em></p>
  
  <p>the input string is:</p>
  
  <pre><code>var inputStrings = [
    'abcdef abcde abc def',
    'abc abc abc',
    'a b c def'
  ];
  </code></pre>
  
  <p>and the output should be:</p>
  
  <pre><code>var outputStrings = [
    'abcdef\nabcde\nabc\ndef',
    'abc\nabc\nabc',
    'a b c\ndef'
  ];
  </code></pre>
  
  <p>I came up with this jsfiddle that passes 2 out of the 3 tests:
  <a href="https://jsfiddle.net/ticuclaudiu/yh269rc0/5/" rel="nofollow">https://jsfiddle.net/ticuclaudiu/yh269rc0/5/</a></p>
  
  <pre><code>function wordWrap(str, cols) {
    var formatedString = '', 
          wordsArray = [];
  
  
      wordsArray = str.split(' ');
  
    for(var i = 0; i &lt; wordsArray.length; i++) {
  
      if(wordsArray.indexOf(wordsArray[i]) === 0) {
          formatedString += wordsArray[i];
      } else {  
          if(wordsArray[i].length &gt; 1) {
              formatedString += '/n' + wordsArray[i];
          } else {
              formatedString +=' ' + wordsArray[i];
          }
      }
    }
  
    console.log(formatedString);
  }
  
  //wordWrap('abcdef abcde abc def', 5);
  wordWrap('abc abc abc', 5);
  //wordWrap('a b c def', 5);
  
  //'abcdef abcde abc def'    |       'abcdef\nabcde\nabc\ndef',
  //'abc abc abc'                     |       'abc\nabc\nabc',        
  //'a b c def'                           |       'a b c\ndef'
  </code></pre>
  
  <p>But I can't figure out how to pass the second one ('abc abc abc');</p>
  
  <p>It has to be pure javascript.</p>
  
  <p>Any pointers? </p>
  
  <p>Thanks.</p>