How do I replace all line breaks in a string with <br /> elements?

If your concern is just displaying linebreaks, you could do this with CSS.

<div style="white-space: pre-line">Some test
with linebreaks</div>

Jsfiddle: https://jsfiddle.net/5bvtL6do/2/

Note: Pay attention to code formatting and indenting, since white-space: pre-line will display all newlines (except for the last newline after the text, see fiddle).


Without regex:

str = str.split("\n").join("<br />");

This will turn all returns into HTML

str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');

In case you wonder what ?: means. It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later. You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169


This works for input coming from a textarea

str.replace(new RegExp('\r?\n','g'), '<br />');

Tags:

Javascript