Nello studio del C un esercizio può riguardare l'inserimento di un'interruzione di riga in una stringa ad una specifica lunghezza di caratteri. Possiamo implementare qualcosa di simile in JavaScript.
L'esercizio è così concepito:
This function takes a string and an output buffer and a desired width. It then copies the string to the buffer, inserting a new line character when a certain line length is reached. If the end of the line is in the middle of a word, it will backtrack along the string until white space is found.
Dato che JavaScript sul Web lavora prevalentemente con i documenti HTML, ecco una versione similare:
'use strict';
const wordWrap = (str = '', len = 0) => {
if(str.length === 0 || len === 0) {
return str;
}
const parts = str.split(' '),
buffer = [];
for(let i = 0; i < parts.length; i++) {
let n = i + 1;
if(n === len) {
buffer.push('<br>');
} else {
buffer.push(parts[i]);
}
}
return buffer.join(' ');
};