nl2br-equivalent-javascript-function


Mariashakoor1111

Uploaded on Oct 7, 2026

Category Technology

nl2br equivalent in JavaScript: use regex to convert newlines to <br> tags, escape HTML safely, and learn simpler CSS and React alternatives.

Category Technology

Comments

                     

nl2br-equivalent-javascript-function

JAVASCRIPT GUIDE nl2br Equivalent str.replace( JavaScript Function /\r\n|\r|\n/g, '' Convert line breaks to safely - by Scriptbaker ); nl2br Equivalent JavaScript Function: A Complete Guide If you've worked with PHP, you've probably used nl2br() to turn line breaks in plain text into HTML tags. JavaScript has no built-in nl2br, but it takes only a few lines of code to replicate. This guide covers the main approaches, when to use each, and how to avoid the security pitfalls. What Does nl2br() Do in PHP? PHP's nl2br() inserts an HTML line break () before every newline character in a string. It's commonly used to display text from a textarea, comment form, or database exactly as the user typed it. echo nl2br("Line one\nLine two"); // Output: Line one // Line two HTML ignores raw newline characters, so without conversion, multi-line text collapses into one line in the browser. The Basic nl2br Equivalent in JavaScript The simplest equivalent uses String.prototype.replace() with a regular expression: function nl2br(str) { if (typeof str !== 'string') return ''; return str.replace(/\r\n|\r|\n/g, ''); } console.log(nl2br('Hello\nWorld')); // Output: HelloWorld How it works: • \r\n matches Windows-style line endings • \r matches old Mac-style line endings • \n matches Unix/Linux line endings • The g flag replaces every match, not just the first Matching \r\n first prevents a Windows line break from being counted as two separate breaks. Matching PHP's Behavior Exactly Scriptbaker | scriptbaker.com Page 1 PHP's version keeps the original newline after the . To mirror that output, use a capture group: function nl2br(str, isXhtml = true) { if (typeof str !== 'string') return ''; const breakTag = isXhtml ? '' : ''; return str.replace(/(\r\n|\r|\n)/g, breakTag + '$1'); } console.log(nl2br('Line one\nLine two')); // Output: Line one // Line two The $1 re-inserts the matched newline after the tag, just as PHP does. This matters little in the browser, but it helps when you're comparing output or porting PHP code. Using replaceAll() in Modern JavaScript If you only need to handle one type of line ending, replaceAll() is a clean option: const text = 'First line\nSecond line\nThird line'; const html = text.replaceAll('\n', ''); It's readable, but it won't catch \r\n or \r. For user-submitted content, the regex version is safer because you can't control what operating system the text came from. Security Warning: Escape HTML First If the text comes from users, never insert the output of nl2br into the page with innerHTML without escaping it first. Otherwise you open the door to cross-site scripting (XSS) attacks. function escapeHtml(str) { return str .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } function safeNl2br(str) { if (typeof str !== 'string') return ''; return escapeHtml(str).replace(/\r\n|\r|\n/g, ''); } document.getElementById('output').innerHTML = safeNl2br(userInput); Always escape first, then convert newlines. If you reverse the order, you'll escape the tags you just added. A Better Alternative: CSS white-space Often you don't need nl2br at all. CSS can render newlines for you: Scriptbaker | scriptbaker.com Page 2 .preserve-lines { white-space: pre-line; } // JavaScript document.getElementById('output').textContent = userInput; • white-space: pre-line preserves line breaks and collapses extra spaces. • white-space: pre-wrap preserves line breaks and all spacing. Because you're using textContent, there's no HTML injection risk. This is the cleanest approach for displaying plain text. nl2br in React React escapes strings by default, so avoid dangerouslySetInnerHTML. Instead, split the text and render the elements directly: function Nl2br({ text }) { return text.split(/\r\n|\r|\n/).map((line, index, arr) => ( {line} {index < arr.length - 1 && } )); } // Usage This is safe by design, and it produces real React elements rather than an HTML string. The Reverse: br2nl in JavaScript To convert tags back into newlines, for example when populating a textarea for editing: function br2nl(str) { return str.replace(//gi, '\n'); } console.log(br2nl('HelloWorld!')); Which Method Should You Use? Situation Best approach Quick conversion of trusted text replace(/\r\n|\r|\n/g, '') Mirroring PHP output exactly Regex with the $1 capture group Displaying user-submitted text Escape HTML, then convert, or use CSS pre-line React or other frameworks Split on newlines and render elements Scriptbaker | scriptbaker.com Page 3 Situation Best approach Plain text display with no HTML white-space: pre-line with textContent Common Mistakes to Avoid 1. Replacing only \n: Text from Windows users contains \r\n, which can leave stray characters behind. 2. Forgetting the global flag: replace(/\n/, '') only replaces the first match. 3. Skipping HTML escaping: This is the most common cause of XSS vulnerabilities in this pattern. 4. Using innerHTML unnecessarily: If CSS can solve the problem, it's usually the safer choice. Final Thoughts Replicating PHP's nl2br in JavaScript is simple: a single regex replace handles the conversion. The real decision is whether you need it at all. For trusted content, the regex function is enough. For user-generated content, escape first or let CSS do the work. NEED HELP WITH YOUR WEBSITE'S DEVELOPMENT OR SEO? Clean code is only half of a high-performing website. At Scriptbaker, we combine technical development expertise with data-driven SEO and digital marketing, so your site runs well and gets found. Whether you need a developer to fix front-end issues, a technical SEO audit, or a content strategy that ranks, our team is ready to help. Contact Scriptbaker today and let's build something that performs. Scriptbaker | scriptbaker.com Page 4