How to add a new line in textarea element?

Solution 1:

Try this one:

    <textarea cols='60' rows='8'>This is my statement one.&#13;&#10;This is my statement2</textarea>

&#10; Line Feed and &#13; Carriage Return are HTML entitieswikipedia. This way you are actually parsing the new line ("\n") rather than displaying it as text.

Solution 2:

Break enter Keyword line in Textarea using CSS:

white-space: pre-wrap;

Solution 3:

I think you are confusing the syntax of different languages.

  • &#10; is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).

  • \n is the linefeed character literal (ASCII 10) in a Javascript string.

  • <br/> is a line break in HTML. Many other elements, eg <p>, <div>, etc also render line breaks unless overridden with some styles.

Hopefully the following illustration will make it clearer:

T.innerText = "Position of LF: " + t.value.indexOf("\n");

p1.innerHTML = t.value;
p2.innerHTML = t.value.replace("\n", "<br/>");
p3.innerText = t.value.replace("\n", "<br/>");
<textarea id="t">Line 1&#10;Line 2</textarea>

<p id='T'></p>
<p id='p1'></p>
<p id='p2'></p>
<p id='p3'></p>

A few points to note about Html:

  • The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A <a href='x'>link</a>.</textarea> to see.
  • The P element renders all contiguous white spaces (including new lines) as one space.
  • The LF character does not render to a new line or line break in HTML.
  • The TEXTAREA renders LF as a new line inside the text area box.

Solution 4:

I've found String.fromCharCode(13, 10) helpful when using view engines. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode

This creates a string with the actual newline characters in it and so forces the view engine to output a newline rather than an escaped version. Eg: Using NodeJS EJS view engine - This is a simple example in which any \n should be replaced:

viewHelper.js

exports.replaceNewline = function(input) {
    var newline = String.fromCharCode(13, 10);
    return input.replaceAll('\\n', newline);
}

EJS

<textarea><%- viewHelper.replaceNewline("Blah\nblah\nblah") %></textarea>

Renders

<textarea>Blah
blah
blah</textarea>

replaceAll:

String.prototype.replaceAll = function (find, replace) {
    var result = this;
    do {
        var split = result.split(find);
        result = split.join(replace);
    } while (split.length > 1);
    return result;
};