Javascript strings wrap

Viewed 6652

I'm trying to find a solution for the following test: you should be able to wrap lines at a given number of columns, without breaking words

the input string is:

var inputStrings = [
  'abcdef abcde abc def',
  'abc abc abc',
  'a b c def'
];

and the output should be:

var outputStrings = [
  'abcdef\nabcde\nabc\ndef',
  'abc\nabc\nabc',
  'a b c\ndef'
];

I came up with this jsfiddle that passes 2 out of the 3 tests: https://jsfiddle.net/ticuclaudiu/yh269rc0/5/

function wordWrap(str, cols) {
  var formatedString = '', 
        wordsArray = [];


    wordsArray = str.split(' ');

  for(var i = 0; i < wordsArray.length; i++) {

    if(wordsArray.indexOf(wordsArray[i]) === 0) {
        formatedString += wordsArray[i];
    } else {  
        if(wordsArray[i].length > 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'

But I can't figure out how to pass the second one ('abc abc abc');

It has to be pure javascript.

Any pointers?

Thanks.

2 Answers
Related