-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapplyLineBreaks.js
More file actions
36 lines (28 loc) · 867 Bytes
/
applyLineBreaks.js
File metadata and controls
36 lines (28 loc) · 867 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* @author 5antos#4876
* @param {string} string Target string
* @param {number} maxCharLengthPerLine Maximum number of characters allowed per line
* @returns {string} String after all line breaks applied
*/
function applyLineBreaks(string, maxCharLengthPerLine) {
const split = string.split(' ')
const chunks = []
for (var i=0, j=0; i < split.length; i++) {
if ((chunks[j] + split[i]).length > maxCharLengthPerLine) j++
chunks[j] = (chunks[j] || '') + split[i] + ' '
}
return chunks.map(c => c.trim()).join('\n')
}
// Example Outputs:
applyLineBreaks('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 30)
/*
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
*/
applyLineBreaks('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 20)
/*
Lorem ipsum dolor
sit amet,
consectetur
adipiscing elit.
*/