1

When I type in a non-resizeable text area something like hello world, this is a demo and the text area is small enough, it will look like this:

hello world,
this is a demo

This is not caused by a \n or something. How can I detect this natural line break in a text area? A fiddle can be found here: http://jsfiddle.net/yx6B7/ As you can see, there is a line break, but javascript just says that it's one big line without any line-breaks in it.

  • possible duplicate of [finding "line-breaks" in textarea that is word-wrapping ARABIC text](http://stackoverflow.com/questions/4719777/finding-line-breaks-in-textarea-that-is-word-wrapping-arabic-text) – Flash Thunder Jan 23 '14 at 14:20
  • detect and then...? What's the ultimate goal? – georg Jan 23 '14 at 14:38
  • @thg435: To convert those line-breaks to real breaks. –  Jan 28 '14 at 14:32

2 Answers2

0

Finally I found this script on the internet:

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;
    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;
    }
}
oTextarea.setAttribute("wrap", "");
document.getElementById("pnlPreview").innerHTML = oTextarea.value.replace(new RegExp("\\n", "g"), "<br />");

}

Which is working fine.

-1

This isn't a javascript problem.

Look at the word-wrap, white-space and overflow css properties.

Pierre Arlaud
  • 4,040
  • 3
  • 28
  • 42