UNPKG

1.11 kBJavaScriptView Raw
1/**
2 * Wraps words in a text with a given width.
3 * @param {string} text The text to wrap. This text can be multiline.
4 * @param {int} width Width of the text. Default = 79.
5 * @return {string} The wrapped text.
6 */
7var text_wrap = function (text, width) {
8 width = width || 79;
9
10 lines = text.split("\r\n");
11
12 return lines
13 .map(function (line){
14 return line_wrap(line, width);
15 })
16 .join("\r\n");
17}
18
19/**
20 * Wraps words in a line with a ligen width.
21 * @param {string} text The line to wrap.
22 * @param {int} width Width of the text. Default = 79.
23 * @return {string} The wrapped text.
24 */
25var line_wrap = function (text, width) {
26 width = width || 79;
27
28 var return_text = "";
29 var words = text.split(' ');
30 var line = "";
31
32 words.forEach(function(word) {
33
34 if ((line.length + word.length) > width) {
35 return_text += "\r\n";
36 line = "";
37 }
38
39 return_text += (line.length == 0 ? "" : " ") + word;
40 line += (line.length == 0 ? "" : " ") + word;
41 });
42
43 return return_text;
44}
45
46module.exports = {
47 text_wrap: text_wrap,
48 line_wrap: line_wrap
49}
\No newline at end of file