I'm using a textarea to enable users to input comments. However, if the users enters new lines, the new lines don't appear when they are outputted. Is there any way to make the line breaks stay.
Any idea how do preserve the line breaks?
To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.
Just put the output text between <pre></pre> tags, that will preserve the line breaks.
-- Using both \r\n SELECT 'First line. \r\nSecond Line. ' AS 'New Line'; -- Using both \n SELECT 'First line.
To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.
Two solutions for this:
PHP function nl2br()
:
e.g.,
echo nl2br("This\r\nis\n\ra\nstring\r"); // will output This<br /> is<br /> a<br /> string<br />
Wrap the input in <pre></pre>
tags.
See: W3C Wiki - HTML/Elements/pre
Here is what I use
$textToOutput = nl2br(htmlentities($text, ENT_QUOTES, 'UTF-8'));
$text
is the text that needs to be displayed $textToOutput
is the returned text from nl2br
and htmlentities
so it can be safety displayed in the html context.ENT_QUOTES
will convert both double and single quotes, so you'll have no trouble with those.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With