Problem:
Convert all line breaks in a given string to HTML
elements, replacing plain line breaks with line breaks suitable for web display.
Example:
Consider a string containing line breaks as follows:
"This is man. Man like dog. Man like to drink. Man is the king."
The desired output after JavaScript conversion should appear like:
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
Solution:
To achieve this conversion, utilize the following JavaScript code:
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
Explanation:
The non-capturing group (?:...)::
The above is the detailed content of How to Replace Line Breaks with `` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!