Handling Line Breaks in HTML 

//

user

So here’s the issue:
You let users input text into a <textarea>, save that value into a database, and then try to display it somewhere else in HTML.

But no matter how many line breaks they entered, it always shows up as a single line. What gives?

Let’s unpack this.


The Problem: Line Breaks Not Rendering in HTML

When a user presses Enter inside a <textarea>, it inserts a newline character (\n).
Yes—it looks like a new line inside the form.

But when you later echo or print that value back into the browser, HTML doesn’t treat \n as a line break.

HTML doesn’t understand \n

HTML needs a tag like <br> to create line breaks visually.

Even though \n is present in the page source, it won’t render on the screen unless it’s converted to something HTML recognizes.


The Fix: Convert \n to <br> Before Displaying

Here’s a simple JavaScript example using a form:

<form name="cf" onsubmit="return replaceBR();">
<textarea id="c"></textarea>
</form>

When the form is submitted, run this function:

function replaceBR() {
document.cf.c.value = document.cf.c.value.replace(/\n/gi, '<br/>');
return true;
}

Key notes:

  • The replace() function by default only replaces the first match.
  • To replace all \n characters, use a regular expression with global (g) and case-insensitive (i) flags: /\n/gi
  • Don’t wrap the regex in quotes!
    This will break it:javascript복사편집// ❌ Wrong replace("\n", "<br/>");

Pro Tip: Double-check Your <br/> Tag

If you’re viewing this in a code highlighter or markdown renderer, be aware that sometimes <br/> can be auto-closed or misinterpreted.

In plain HTML/JS, the following is perfectly fine:

value.replace(/\n/g, "<br/>");

Alternative: Server-side Conversion (PHP example)

If you’re working with PHP, use:

echo nl2br($textarea_value);

nl2br() automatically converts all \n to <br> tags before outputting.


Final Thoughts

Textareas may let users enter line breaks, but browsers won’t display them unless you explicitly convert \n to <br>.

Remember:

  • \n = works in text input
  • <br> = works in HTML output

Don’t waste time wondering why your text is flattened. Use replace() in JavaScript or nl2br() in PHP and you’re good to go!

Leave a Comment