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

How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?

Example:

A variable passed from PHP as below:

  "This is man.

     Man like dog.
     Man like to drink.

     Man is the king."

I would like my result to look something like this after the JavaScript converts it:

  "This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."

Solution 1:

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

Solution 2:

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).

Solution 3:

Without regex:

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

Solution 4:

This works for input coming from a textarea

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

Solution 5:

If the accepted answer isn't working right for you then you might try.

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

It worked for me.