Skip to content

Instantly share code, notes, and snippets.

@formix
Last active March 4, 2021 15:20
Show Gist options
  • Save formix/29e4dcbefb17403e53b3 to your computer and use it in GitHub Desktop.
Save formix/29e4dcbefb17403e53b3 to your computer and use it in GitHub Desktop.
JavaScript Word Wrap
/**
* Wrap text to a maximum of 78 char per line. Indent the text using the number
* of spaces specified by indent.
*/
function wrap(text, indent) {
if (!text) {
console.log();
return;
}
var col = 0;
var words = text.split(/ /g);
var firstWord = true;
for (var i = 0; i < words.length; i++) {
if (col == 0) {
firstWord = true;
if (indent) {
for (var j = 0; j < indent; j++) {
process.stdout.write(" ");
col++;
}
}
}
var word = words[i];
if ((col + word.length) > 78) {
console.log();
col = 0;
i--;
} else {
if (!firstWord) {
process.stdout.write(" ");
col++;
}
process.stdout.write(word);
col += word.length;
firstWord = false;
}
}
console.log();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment