Skip to content

Instantly share code, notes, and snippets.

@kkoppenhaver
Created May 13, 2016 18:27
Show Gist options
  • Save kkoppenhaver/f5d4790cedc01f8459d835d1c0198f4f to your computer and use it in GitHub Desktop.
Save kkoppenhaver/f5d4790cedc01f8459d835d1c0198f4f to your computer and use it in GitHub Desktop.
function format(text, width) {
var formatted = '';
var words = text.split(' ');
var line_length = 0;
words.map(function(value, index){
// The first word shouldn't have a space before it, and the length check shouldn't
// add any extra to the line count
if( index == 0){
addition = 0;
}
else {
addition = 1;
}
// If adding the word won't push us over the edge...
if(line_length + value.length + addition <= width){
// If this is the first word of the first line, don't include a space
if(addition == 1) {
// Append the word to the string
formatted += ' ' + value;
}
else {
// Append the word to the string
formatted += value;
}
// And update the current length of the line
line_length += value.length + addition;
}
else {
// Add a new line character and append the word to the new line
formatted += '\n';
// Reset char count
line_length = 0;
// Append the word to the string
formatted += value;
// And update the current length of the line
line_length += value.length;
}
});
return formatted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment