JAVASCRIPT

Convert Newlines to HTML <br> Tags

Automatically replace all newline characters (`\n`, `\r\n`) in a string with HTML `<br>` tags for web display.

function convertNewlinesToBr(text) {
    // Use /\r?
/g to catch both 
 and \r
 (Windows style) newlines
    return text.replace(/\r?
/g, '<br>');
}

const userText = "Hello world!
This is a new line.\r
And another one.";
console.log(convertNewlinesToBr(userText));
// Expected Output: "Hello world!<br>This is a new line.<br>And another one."
How it works: The regex `/\r? /g` is designed to match various newline character sequences. `\r?` optionally matches a carriage return (which is part of Windows-style newlines `\r `), followed by a mandatory newline character ` `. The `g` flag ensures that all occurrences of newlines throughout the string are replaced. The `replace()` method then substitutes these matched newline sequences with the HTML `<br>` tag, making user-entered breaks visible in web content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs