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."
Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With