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.