Home >Web Front-end >JS Tutorial >How to Replace Line Breaks with `` Tags in JavaScript?

How to Replace Line Breaks with `` Tags in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 02:23:08830browse

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:

  • (?:rn|r|n): This non-capturing group matches any of the following newline characters: CR LF (rn), CR (r), or LF (n).

Non-Capturing Group:

  • The ?: syntax marks the group as non-capturing, which means the matched text won't be stored for future use.

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:

  • The g flag is used to perform a global find and replace, ensuring all line breaks are converted.
  • For more information on non-capturing groups, refer to the following resources:

    • https://stackoverflow.com/a/11530881/5042169
    • https://stackoverflow.com/a/36524555/5042169

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn