How to show newlines from textarea in a table?

12,166

Solution 1

\n won't be rendered as a new line in HTML. You have to use a <br/> to achieve this effect.

Use a string replace to replace all '\n' characters to '<br/>'

If you are using a server side language like C# you can do this

private string PutLineBreaks(string strData)
{
    string strReplaced = string.Empty;

    Regex r = new Regex("/\n/g");

    strReplaced = r.Replace(strData, "<br/>");

    return strReplaced;
}

Solution 2

Set your css in the table cell to

white-space:pre-wrap;

Solution 3

Set your css in the table cell to

white-space:pre-line;

Even if your data has trailing spaces it would remove and make data perfect.

Solution 4

You want to replace all \n with <br/>.

Share:
12,166

Related videos on Youtube

Gnark
Author by

Gnark

Updated on June 04, 2022

Comments

  • Gnark
    Gnark over 1 year

    In a form I have a textarea where obviously text is entered. When the input is finished the content gets submitted to the server and is being stored in a database...

    When I display the input the user made within a table, the newlines are not visible. When I inspect the source the newlines are there, but within a table the newlines do not work...

    Is there any possibility of displaying the linebreaks within that table? I know, probably a really silly question but I'm not to pro when it comes to things like html and css...

    Any help is really appreciated!

  • Deniz Dogan
    Deniz Dogan about 14 years
    I'm not sure replacing \n with a <p></p> would be semantically correct actually. <br /> is semantically a line break, as is \n. \n\n however would semantically be a paragraph.
  • Gnark
    Gnark about 14 years
    actually, Id rather use a little JavaScript snippet to accomplish that task! anyway, thanks for the info!
  • Jarrett Meyer
    Jarrett Meyer about 14 years
    You'd want to start the entire text block with a '<p>', and close the entire text block with a '</p>'. Then you can replace each '\n' with a '</p><p>', which will close one paragraph and start another.
  • Brian M. Hunt
    Brian M. Hunt about 12 years
    The \n is rendered as a newline within <pre> tags, or in any block with various settings (e.g. 'pre', 'pre-line') of the white-space CSS setting, see e.g. w3schools.com/cssref/pr_text_white-space.asp
  • Ilia
    Ilia over 9 years
    It works, and now you can keep /n without replacing it to <br>. Thanks, vsync! P.S. Amazing home page - great job!
  • Rishi Jasapara
    Rishi Jasapara over 8 years
    This should be the selected answer. Such a simple way!
  • 72GM
    72GM over 8 years
    yeah this is the best way
  • Sincere
    Sincere almost 7 years
    This is the best answer. In my case white-space: pre-line; worked better. Thanks