Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:43
Show Gist options
  • Save rfprod/c8f5f4509ce0660c3d4c8acc470132ae to your computer and use it in GitHub Desktop.
Save rfprod/c8f5f4509ce0660c3d4c8acc470132ae to your computer and use it in GitHub Desktop.
String Formatter
function format(text, width) {
const input = text.split(' ');
let output = '';
loop1:
for (let i = 0, max = input.length; i < max; i++) {
let row = input[i] + ' ';
let nextWord = input[i + 1];
loop2:
while (typeof nextWord !== 'undefined') {
if (row.length + nextWord.length > width) { break loop2; }
row = row + nextWord + ' ';
i++;
nextWord = input[i + 1];
}
output = (i < max - 1) ? output + row.trim() + '\n' : output + row.trim();
}
return output;
}
format('test test test test test', 10);
/*
test test\n
test test\n
test
*/

String Formatter

Function format() formats text string according to provided width argument.

  • Each line contains as many words as possible.
  • Strings do not start or end with spaces.
  • New lines are separated with \n.
  • Last string does not contain \n.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment