This tutorial shows how to replace all the line breaks with <br> in JavaScript. We can do this by
- Using Regex
- Using Built-in Methods
1. Using Regex
Syntax
string.replace(/(\r\n|\r|\n)/g, '<br>')
The RegEx /(\r\n|\r|\n)/g
checks for line breaks across all the string and replace()
function replaces the line breaks with <br>
.
Example 1
// program to replace all line breaks in a string with <br> using RegEx
const string = `Today is sunday.
Tomorrow is monday.
Yesterday was saturday.`;
const result = string.replace(/(\r\n|\r|\n)/g, '<br>');
console.log(result);
Output
Today is sunday.<br>Tomorrow is monday.<br>yesterday was saturday.
2. Using Built-in Methods
Syntax
string.split('\n').join('<br>')
The split("\n")
splits the line breaks of a string into array elements and the join(“<br>”) joins the array by adding <br> between array elements.
Example 2
// program to replace all line breaks in a string with <br> using built-in methods
const string = `Today is sunday.
Tomorrow is monday.
Yesterday was saturday.`;
const result = string.split('\n').join('<br>');
console.log(result);
Output
Today is sunday.<br>Tomorrow is monday.<br>yesterday was saturday.