In JavaScript, you can convert all line breaks within a string to HTML
elements using regular expressions. This is useful when you want to display multi-line text that maintains its formatting.
Implementation:
To replace all line breaks with
elements, use the following regular expression:
str.replace(/(?:\r\n|\r|\n)/g, '<br />');
Explanation:
Example:
Consider a variable str with the following value:
"This is man. Man like dog. Man like to drink. Man is the king."
After applying the replacement, the result will be:
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
Non-Capturing Groups:
The ?: syntax surrounding the line break patterns creates a non-capturing group. This means that the line break characters are not captured into memory for later reference, which can improve performance for large strings.
The above is the detailed content of How Can I Convert Line Breaks to HTML `` Tags in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!