Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript strings wrap [closed]

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.

like image 827
Claudiu Ticu Avatar asked Nov 06 '25 04:11

Claudiu Ticu


1 Answers

The answer seems to be:

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


    wordsArray = str.split(' ');

    formatedString = wordsArray[0];

    for (var i = 1; i < wordsArray.length; i++) {
        if (wordsArray[i].length > cols) {
            formatedString += '\n' + wordsArray[i];
        } else {
            if (formatedString.length + wordsArray[i].length > cols) {
                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);

you can see jsfiddle here https://jsfiddle.net/ticuclaudiu/yh269rc0/13/

like image 129
Claudiu Ticu Avatar answered Nov 07 '25 19:11

Claudiu Ticu