← Back to all snippets
JAVASCRIPT

Convert Newlines to HTML Line Breaks

Learn to use a simple yet powerful regular expression to replace all newline characters in a string with HTML <br /> tags, preparing user-generated text for safe display in web browsers.

function nl2br(text) {
  return text.replace(/\r?
/g, '<br />');
}
How it works: This JavaScript function provides a practical way to format multiline text for HTML display. It employs a regular expression (`/\r? /g`) to find all occurrences of both Windows-style (`\r `) and Unix-style (` `) newline characters globally within a string, replacing them with appropriate HTML `<br />` tags to preserve line breaks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs