Scriptbaker
SCRIPTBAKERAI & Software Engineering
JavaScript

nl2br equivalent JavaScript function

Learn how to create an <code>nl2br()</code> equivalent in JavaScript to convert newline characters into HTML line breaks. This guide covers simple JavaScript functions, PHP-to-JavaScript conversion, textarea handling, different newline formats, secure DOM methods, CSS alternatives, and important XSS considerations when working with user-generated content.

· 5 min read · By Tahir Yasin

PHP provides a useful nl2br() function that inserts HTML line breaks before all newlines in a string. When working with JavaScript, you may need the same functionality to convert line breaks such as \n, \r\n, and \r into HTML <br> elements.

JavaScript does not have a built-in nl2br() equivalent, but you can easily create a custom function using a regular expression. This is particularly useful when displaying text entered by users, converting plain-text content to HTML, or migrating functionality from PHP to JavaScript.

JavaScript Equivalent of PHP nl2br()

The following function provides a JavaScript equivalent of PHP's nl2br() function:

function nl2br(str, is_xhtml) {    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined')        ? '<br />'        : '<br>';    return (str + '').replace(        /([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,        '$1' + breakTag + '$2'    );}

How to Use nl2br() in JavaScript

Once the function has been defined, you can pass a string containing newline characters to it.

var text = "Hello World\nWelcome to ScriptBaker";var result = nl2br(text);console.log(result);

The converted result will contain an HTML line break:

Hello World<br />Welcome to ScriptBaker

When inserted into an HTML element, the text will appear on separate lines.

Why Do You Need an nl2br Equivalent in JavaScript?

Newline characters and HTML line breaks are not the same thing. A JavaScript string can contain \n to represent a new line, but HTML normally collapses whitespace when displaying regular text.

For example:

var message = "Line one\nLine two\nLine three";

If this string is displayed directly as HTML, the newline characters may not create visible line breaks. Converting the newlines into <br> elements allows the browser to display each line separately.

Understanding the nl2br JavaScript Function

Let's break the function into smaller parts to understand how it works.

1. Defining the Break Tag

var breakTag = (is_xhtml || typeof is_xhtml === 'undefined')    ? '<br />'    : '<br>';

This determines whether the function should generate the XHTML-style <br /> tag or the HTML5-style <br> tag.

If is_xhtml is true, or if the parameter is not provided, the function uses:

<br />

If is_xhtml is false, it uses:

<br>

2. Converting the Input to a String

(str + '')

This ensures that the value being processed is treated as a string before the replacement operation is performed.

3. Finding Newline Characters

The regular expression handles different newline formats:

/\r\n|\n\r|\r|\n/g

This covers common line-ending formats used across operating systems and applications.

  • \n line feed
  • \r\n — carriage return followed by line feed
  • \r carriage return

4. Replacing Newlines with HTML Breaks

The replace() method finds newline characters and replaces them with the selected HTML break tag.

str.replace(regex, '$1' + breakTag + '$2');

This produces HTML that the browser can use to display the original line structure.

Simple nl2br Function in Modern JavaScript

If you only need a straightforward conversion of newline characters to HTML line breaks, you can use a simpler function:

function nl2br(str) {    return str.replace(/\r?\n/g, '<br>');}

Example:

const text = "First line\nSecond line\nThird line";console.log(nl2br(text));

This approach is easier to read and is sufficient for many basic applications.

Using nl2br with Textarea Values

A common use case is converting text entered into a <textarea> into HTML.

<textarea id="message"></textarea><div id="output"></div>

You can retrieve the textarea value and convert its newline characters:

const message = document.getElementById('message').value;document.getElementById('output').innerHTML = nl2br(message);

This allows multiline plain text to be displayed with visible line breaks.

Important Security Consideration When Using innerHTML

When converting user-provided text into HTML, be careful with innerHTML. Simply replacing newline characters with <br> does not sanitize HTML that may already exist in the input.

For example, if untrusted user input is inserted directly into innerHTML, malicious HTML or JavaScript could potentially be interpreted by the browser.

If you only need to display plain text safely, prefer textContent rather than inserting untrusted content with innerHTML.

For example:

const output = document.getElementById('output');output.textContent = message;

Another option is to convert the text into DOM nodes and explicitly create <br> elements instead of treating the complete string as HTML.

nl2br JavaScript Function Using DOM Elements

If the input is untrusted and you want to preserve line breaks without interpreting HTML, you can build the output using DOM APIs:

function nl2brSafe(str, element) {    const lines = String(str).split(/\r\n|\n\r|\r|\n/);    lines.forEach((line, index) => {        element.appendChild(document.createTextNode(line));        if (index < lines.length - 1) {            element.appendChild(document.createElement('br'));        }    });}

This approach keeps the input as text while adding actual <br> elements to the DOM.

Handling Different Newline Characters

When processing text from different systems, newline characters may vary. A robust implementation should account for the common formats:

\n\r\n\r

The regular expression in the original PHP-compatible implementation is designed to handle these different line-ending styles.

nl2br with ES6 JavaScript

If you are working with modern JavaScript, you can use const and template-friendly syntax to create a cleaner implementation:

function nl2br(str, isXhtml = true) {    const breakTag = isXhtml ? '<br />' : '<br>';    return String(str).replace(/\r\n|\r|\n/g, breakTag);}

Example:

const text = `Hello,Welcome to our website.This is a multiline message.`;console.log(nl2br(text));

Common Use Cases for nl2br in JavaScript

An nl2br() equivalent can be useful in many web development scenarios, including:

  • Displaying multiline comments
  • Formatting contact form messages
  • Showing user-generated content
  • Displaying product descriptions
  • Converting plain-text notes into HTML
  • Formatting chat messages
  • Displaying API responses containing newline characters
  • Converting legacy PHP functionality to JavaScript
  • Formatting multiline error or status messages

Alternative: Preserve Line Breaks with CSS

In some cases, you do not need to convert newline characters into <br> elements at all. CSS can preserve whitespace and line breaks when displaying plain text.

.preserve-line-breaks {    white-space: pre-line;}

Then you can safely display the text as text:

const output = document.getElementById('output');output.classList.add('preserve-line-breaks');output.textContent = message;

This can be a cleaner option when your goal is simply to preserve the formatting of plain text rather than generate HTML.

PHP nl2br vs JavaScript Equivalent

The main difference is that PHP provides nl2br() as a built-in function, while JavaScript requires you to implement the behavior yourself or use another formatting approach.

Feature PHP JavaScript
Built-in nl2br function Yes No
Newline replacement nl2br() replace() with regex
Custom implementation Usually unnecessary Common approach
Alternative formatting HTML output CSS white-space

Frequently Asked Questions

Does JavaScript have an nl2br() function?

No. JavaScript does not provide a built-in function named nl2br() like PHP. You can create an equivalent using String.replace() and a regular expression.

How do I convert newline characters to br tags in JavaScript?

You can use the following simple function:

function nl2br(str) {    return String(str).replace(/\r\n|\r|\n/g, '<br>');}

What does \n mean in JavaScript?

\n represents a line feed or newline character in a JavaScript string. It is commonly used to create a new line in text.

What is the difference between \n and <br>?

\n is a newline character inside a string, while <br> is an HTML element that creates a visible line break when rendered by a browser.

Can I use nl2br with a textarea?

Yes. A textarea value can contain newline characters, and an nl2br() equivalent can convert those characters into HTML line breaks when appropriate.

Is using innerHTML with nl2br safe?

Not necessarily. If the source string comes from an untrusted user, inserting it through innerHTML can create an XSS risk. For plain-text content, prefer textContent or create <br> elements through the DOM.

Can CSS replace nl2br in JavaScript?

Yes. If your goal is simply to preserve line breaks in plain text, CSS such as white-space: pre-line; can often eliminate the need to convert newline characters into HTML.

Which nl2br JavaScript implementation should I use?

For simple trusted content, a replace()-based function is usually sufficient. For untrusted content, displaying the value with textContent and using CSS or DOM-created <br> elements is safer.

Conclusion

Although JavaScript does not have a built-in nl2br() function, creating a PHP nl2br() equivalent is straightforward using regular expressions and the replace() method.

The function can be useful when working with multiline strings, textarea values, comments, chat messages, and other text-based content. However, when dealing with user-generated content, always consider HTML injection and XSS risks before inserting converted strings with innerHTML.

For simple plain-text formatting, CSS white-space or safe DOM manipulation may be a better solution than converting text into HTML.

Need Help With JavaScript or Web Development?

Need help building or improving a JavaScript, PHP, or web application? ScriptBaker can help with custom web development, API integrations, application modernization, automation, and ongoing maintenance.

Contact SCRIPTBAKER to discuss your web development project and find the right technical solution.