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

How to Replace Line Breaks with `` in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-01 01:00:111000browse

How to Replace Line Breaks with `` in JavaScript?

How to Replace Line Breaks with
Elements Using JavaScript

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:

  • (?:rn|r|n): This regex pattern matches all types of line breaks, including carriage returns (r) and newlines (n).
  • g: The g flag ensures that all matches are replaced.

  • : The replacement string is the HTML
    element, which represents a line break.

The non-capturing group (?:...)::

  • It prevents the matched line breaks from being captured and stored in memory, which helps improve performance and memory usage.

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!

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