Tengo un área de texto para hacer una entrada de texto. Ahora necesito dividir el texto en una matriz de palabras y agregar las palabras palabra por palabra en un div hasta que mi div sea más grande que mis filas dadas. Las palabras que son demasiado largas deben dividirse con un guión y agregarse a la siguiente fila. El problema es que el texto sale del ancho máximo. ¿Cómo puedo hacer que las palabras agregadas permanezcan en el ancho máximo y dejar de agregar nuevas palabras si se alcanzan las filas máximas? Intenté hacerlo así:
function textfield_handler() { let text = document.getElementById("tf-input").value.toString().split(/\s+/); let T1 = document.getElementById("tf-T1"); let maxrows_top = document.getElementById("tf-toprows").value; T1.innerText = ""; while (T1.getClientRects().length <= maxrows_top) { if(text.length === 0) break; let word = text.shift(); T1.innerHTML += '<a href="#">' + word + '</a>' + '\xa0'; } } .textline { margin: 0 auto; width: 100%; text-align: justify; } div.textline { -webkit-hyphens: auto; -moz-hyphens: auto; -ms-hyphens: auto; hyphens: auto; } span.textline { -webkit-hyphens: auto; -moz-hyphens: auto; -ms-hyphens: auto; hyphens: auto; } <div> <label>Rows:</label> <input type="number" min="1" id="tf-toprows" value="5"> <textarea id="tf-input"> </textarea> <button type="button" id="generate-textfield" onclick="textfield_handler()">Convert text</button> </div> <div id="textfield-container" class="textline" style="width: 400px; background-color: lightgray;"> <div class="textline" style="min-height: 50px; max-width: 800px" id="tf-T1"> </div>También se usó getClientRects().length para detectar si el texto es más largo de lo que permiten mis filas máximas. Pero estoy buscando una mejor solución en este momento.