Impariamo dal C: interrompere una stringa ad una data lunghezza in JavaScript

Impariamo dal C: interrompere una stringa ad una data lunghezza in JavaScript

Durante lo studio del C ho collezionato una lunga serie di esercizi. Uno di questi riguardava una soluzione per inserire un'interruzione di riga in una stringa ad una data 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:


function wordWrap( str, len ) {
	var parts = str.split( " " ),
		buffer = [];
	    for( var i = 0; i < parts.length; i++ ) {
			var n = i + 1;
			if( n == len ) {
				buffer.push( "<br>" );	
			} else {
				buffer.push( parts[i] );
			}
		}
		
	return buffer.join( " " );
}

Torna su