How do I replace all line breaks in a string with
tags?

How do I replace all line breaks in a string with
tags?

How can I read the line break from a value with Javascript and replace all the line breaks with br tags?
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

Man like dog.
Man like to drink.

Man is the king.”

Solutions/Answers:

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.

HTML

<div class="white-space-pre">Some test
with linebreaks</div>

CSS

.white-space-pre {
    white-space: pre-wrap;
}

jsfiddle
https://jsfiddle.net/yk1angkz/125/

Note: Pay attention to code formatting and indenting, since white-space: pre-wrap will display all whitespaces (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.

Solution 6:

Regardless of the system:

my_multiline_text.replace(/$/mg,'<br>');