How to add a new line in textarea element?
Asked Answered
P

15

363

I want to add a newline in a textarea. I tried with \n and <br/> tag but are not working. You can see above the HTML code. Can you help me to insert a newline in a textarea?

<textarea cols='60' rows='8'>This is my statement one.\n This is my statement2</textarea>

<textarea cols='60' rows='8'>This is my statement one.<br/> This is my statement2</textarea>
Pickmeup answered 25/12, 2011 at 2:12 Comment(0)
R
636

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.

Roche answered 25/12, 2011 at 2:23 Comment(5)
@LittleAlien jsfiddle.net/v0y3xvpx/1 - answer based on the OP question, obviously problem was solvedRoche
isn't just &#10; enough to parse the \n?Chattel
Doesn't it depend on Windows vs. macOS whether both the line-feed and carriage-return characters are needed, or even parsed right?Garganey
@SeizeTheDay yes, but it is not MacOS - it is Linux/BSD vs WindowsRoche
@Roche Oh! I thought macOS, being Unix-based, would still have that issue. But you’re for sure right, the difference is more general.Garganey
H
102

Break enter Keyword line in Textarea using CSS:

white-space: pre-wrap;
Hedgerow answered 29/3, 2019 at 13:16 Comment(2)
it is the simplest method to achieve the required result, thanks @SurajHerrick
This is indeed a good solution, except if you plan to minify your HTML, you would have to preserve these newlinesMickeymicki
T
46

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.
Teriann answered 1/4, 2017 at 1:57 Comment(3)
On the face of it this post seems complicated, but actually contains a LOT of useful information. If you are progamatically adding lines to your <textarea/> this is the post you need!Hudgins
<br/> is what I was looking forBeers
Very useful post indeed. Most newcomers will confuse theseLaryngeal
H
36

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;
};
Huntress answered 23/1, 2015 at 9:7 Comment(3)
The newline = String.fromCharCode(13, 10); is the only thing that worked for me in adding new line programatically during run time. +1 on that.Supen
I would like to suggest perhaps a simpler way for replace all: var regExp = new RegExp(find,"gi"); str=str.replace(regExp,replace);Supen
I did s = s.replace(/\\n/g, String.fromCharCode(13, 10) ). This is magic though. Thank you.Carbuncle
C
32
<textarea cols='60' rows='8'>This is my statement one.

This is my statement2</textarea>

Fiddle showing that it works: http://jsfiddle.net/trott/5vu28/.

If you really want this to be on a single line in the source file, you could insert the HTML character references for a line feed and a carriage return as shown in the answer from @Bakudan:

  <textarea cols='60' rows='8'>This is my statement one.&#13;&#10;This is my statement2</textarea>
Cullan answered 25/12, 2011 at 2:16 Comment(0)
B
12

Try this. It works:

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

Replacing for <br> tags:

$("textarea#test").val(replace($("textarea#test").val(), "<br>", "&#10;")));
Bos answered 25/12, 2011 at 2:18 Comment(1)
its actually $("textarea#test").val().replace(/\n/g, "&#10;"); (this will replace all occurrences of new line)Cabbage
M
7

To get a new line inside text-area, put an actual line-break there:

    <textarea cols='60' rows='8'>This is my statement one.
    This is my statement2</textarea>
Mindimindless answered 25/12, 2011 at 13:39 Comment(0)
J
7

You should also check the css white-space property (mdn docs) of your element, make sure it's set to a value that doesn't suppress line breaks, e.g.:

white-space: pre-line;

You'd be interested in these 3 values:

pre
Sequences of white space are preserved. Lines are only broken at newline characters in the source and at <br> elements.

pre-wrap
Sequences of white space are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

pre-line
Sequences of white space are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

Jemappes answered 29/4, 2022 at 10:2 Comment(0)
C
5

You might want to use \n instead of /n.

Culinarian answered 25/12, 2011 at 2:13 Comment(2)
Well, a literal \n won't work either, it would need to be an actual newline.Dollydolman
Yes, of course. But I'm (incorrectly?) assuming that he already knew this.Culinarian
A
2

After lots of tests, following code works for me in Typescreipt

 export function ReplaceNewline(input: string) {
    var newline = String.fromCharCode(13, 10);
    return ReplaceAll(input, "<br>", newline.toString());
}
export function ReplaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}
Angiology answered 17/8, 2016 at 13:45 Comment(0)
N
0

My .replace()function using the patterns described on the other answers did not work. The pattern that worked for my case was:

var str = "Test\n\n\Test\n\Test";
str.replace(/\r\n|\r|\n/g,'&#13;&#10;');

// str: "Test&#13;&#10;&#13;&#10;Test&#13;&#10;Test"
Naif answered 27/2, 2018 at 16:23 Comment(0)
S
0

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

p3.innerText = t.value.replace("\n", "");

<textarea id="t">Line 1&#10;Line 2</textarea>

<p id='p3'></p>
Signification answered 10/7, 2018 at 6:54 Comment(1)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Arterialize
S
0

If you are using react

Inside the function

const handleChange=(e)=>{
const name = e.target.name;
let value = e.target.value;
value = value.split('\n').map(str => <span>{str}<br/></span>);
SetFileds({ ...fileds, [name]: value });
}
Saltzman answered 4/5, 2021 at 19:0 Comment(0)
P
0

A simple and natural solution not involving CSS styles or numeric character references like &#13;&#10; would be to use the &NewLine; character entity reference:

The cardinal directions are:&NewLine;- North&NewLine;- East&NewLine;- South&NewLine;- West

Note: Since this is defined simply as the LF (line feed, or the U+000A Unicode code point) character, it's not 100% certain whether it suits situations where the entire CR + LF (carriage return + line feed) sequence is required. But then, it worked in my Chrome, Edge and WebView2 tests done on Windows 10, so it should be ok to use.

Pemberton answered 14/5, 2022 at 16:5 Comment(0)
L
-13

just use <br>
ex:

<textarea>
blablablabla <br> kakakakakak <br> fafafafafaf 
</textarea>

result:
blablablabla
kakakakakak
fafafafafaf

Lippizaner answered 5/11, 2018 at 12:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.