JSFiddle - React, Tailwind, and code Playground

by Graham Dixon

HTML

<div>
    <textarea id="myTextarea" ></textarea>
</div>
<div id="pnlPreview"></div>
<div>
    <button type="button" onclick="ApplyLineBreaks('myTextarea');">Apply Line Breaks</button>
</div>

CSS

textarea { font-family: serify; text-align:justify;display:block; width: 800px; font-size:30px; overflow: hidden;}
#pnlPreview { width:800px; font-size:30px; text-align:justify;}

JavaScript

function ApplyLineBreaks(strTextAreaId) {
    var oTextarea = document.getElementById(strTextAreaId);
    if (oTextarea.wrap) {
        oTextarea.setAttribute("wrap", "off");
    }
    else {
        oTextarea.setAttribute("wrap", "off");
        var newArea = oTextarea.cloneNode(true);
        newArea.value = oTextarea.value;
        oTextarea.parentNode.replaceChild(newArea, oTextarea);
        oTextarea = newArea;
    }

    var strRawValue = oTextarea.value;
    oTextarea.value = "";
    var nEmptyWidth = oTextarea.scrollWidth;
   
    var nLastWrappingIndex = -1;
    for (var i = 0; i < strRawValue.length; i++) {
        var curChar = strRawValue.charAt(i);
        if (curChar == ' ' || curChar == '-' || curChar == '+')
            nLastWrappingIndex = i;
        oTextarea.value += curChar;
        // console.log(oTextarea.scrollWidth, nEmptyWidth);
        if (oTextarea.scrollWidth > nEmptyWidth) {
            var buffer = "";
            if (nLastWrappingIndex >= 0) {
                for (var j = nLastWrappingIndex + 1; j < i; j++)
                    buffer += strRawValue.charAt(j);
                nLastWrappingIndex = -1;
            }
            buffer += curChar;
            oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
            oTextarea.value += "\n" + buffer;
             console.log(oTextarea.value);
        }
    }
    oTextarea.setAttribute("wrap", "");console.log(oTextarea.value.replace(new RegExp("\\n", "g"), "<br />"));
  console.log(oTextarea.value); document.getElementById("pnlPreview").innerHTML = oTextarea.value.replace(/\n*?(.*)/g, (match) => {
	return (match ? "<span>" + match + "</span>" : "")
});
    oTextarea.value = oTextarea.value.replace(new RegExp("\\n", "g"), "");
}