I receive the answer ajax from the server in json format of the following form: {"success":true,"data":{"answer":"first line\r\nsecond line boom\r\n123","answer_id":433}}

Then I scatter the data under the places in the formation of the html block and output, i.e. in the right place eg + respose.data.answer +

The problem is that the text in this case is my text, i.e. there are spaces, but line breaks do not work.

There was a thought to insert and replace \n with <br> before inserting into the html regular, but I think this is clearly the wrong solution. How to be?

  • Except for replacing from \r\n to <br> - no way. \r\n is text/plain , and <br> is text/html , if you do not explicitly specify text/plain headers, the browser will not display any hyphenation, unless of course you can go to view-source:http://site.ru/ - then you will see hyphenation, well, or throw it in textarea =) - And

1 answer 1

You can split the string using the .split() method into an array and display each in its <p> tags

 <div id="app"></div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script> const str = "first line\r\nsecond line boom\r\n123"; const list = str.split(/\r\n/); const $p = $('<p class="text" />'); const paragraphs = list.map(txt => { return $p.clone().text(txt); }); $('#app').append(paragraphs); </script> 

  • No, you do not need to wrap a paragraph. There and without that in the paragraph is located. But on the other hand, can you try to split the br'y arrange? What is faster str.split or str.replace (a simple replacement with the flag g)? - Aaron
  • @Aaron .split() splits into an array, at the output ["first line", "second line boom", "123"] . - Alexander Zaytsev