1. ホーム
  2. javascript

[解決済み] How do I replace all line breaks in a string with <br /> elements?

2022-03-15 03:50:28

Question

How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?

Example:

A variable passed from PHP as below:

  "This is man.

     Man like dog.
     Man like to drink.

     Man is the king."

I would like my result to look something like this after the JavaScript converts it:

  "This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."

How to solved?

This will turn all returns into HTML

str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');

In case you wonder what ?: means. これは非捕捉グループと呼ばれるものです。つまり、括弧の中の正規表現はメモリに保存されず、後で参照されるということです。 詳しくは、以下のスレッドを参照してください。
https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169