Home >Web Front-end >JS Tutorial >How to Replace Line Breaks with `` Tags in JavaScript?
Replacing Line Breaks with
Elements Using JavaScript
Transforming line breaks into
elements is essential for displaying multiline text in HTML. To achieve this in JavaScript, a simple yet effective solution exists.
Solution:
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
Breaking Down the Regex:
Non-Capturing Group:
Example:
Given this input string:
"This is man. Man like dog. Man like to drink. Man is the king."
The JavaScript code will replace line breaks with
tags, resulting in the following HTML:
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
Additional Notes:
For more information on non-capturing groups, refer to the following resources:
The above is the detailed content of How to Replace Line Breaks with `` Tags in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!