- Instant help with your JavaScript coding problems

Replace line break with br in JavaScript

Question:
How to replace line break with br in JavaScript?
Answer:
let multilineString = `My
text\r1\r\n2\n3\n\r4
is
here`;

let htmlText = multilineString.replace(/(\r\n|\n\r|\r|\n)/g, '<br>');

console.log('Multiline string: ' + multilineString);
console.log('HTML text: ' + htmlText);
Description:

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If the pattern is a string, only the first occurrence will be replaced.

Reference:
replace() manual
Share "How to replace line break with br in JavaScript?"
Related snippets:
Tags:
javascript, string, replace, newline, line break, br
Technical term:
Replace line break with br in JavaScript