How can I read the line break from a value with JavaScript and replace all the line breaks with
elements?
Example:
A variable passe
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).
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
It will replace all new line with break
str = str.replace(/\n/g, '<br>')
If you want to replace all new line with single break line
str = str.replace(/\n*\n/g, '<br>')
Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm this will help you everytime.
Try
let s=`This is man.
Man like dog.
Man like to drink.
Man is the king.`;
msg.innerHTML = s.replace(/\n/g,"<br />");
<div id="msg"></div>
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.
This works for input coming from a textarea
str.replace(new RegExp('\r?\n','g'), '<br />');