Insert the paragraphs of a JSON file into a DIV

8

I have a file that in its content it contains paragraphs . These paragraphs are separated by \n but when I insert content the paragraphs are not separated and instead of line break I have a space in DIV . In my view my solution would be to convert \n to line breaks that HTML understands ( <p> or <br> ). What is the right method to use?

    
asked by anonymous 12.12.2013 / 13:48

4 answers

10
  

What is the right method to use?

More correct in what sense? Performance? Assertiveness? Readability?

Anyway, a traditional replace of JavaScript is usually used (as seen here , here and here ...).

Then in your case it would be enough:

>>> "string\ncom\nquebras\nde\nlinha".replace(/\n/g, '<br />');
"string<br />com<br />quebras<br />de<br />linha"

Now, to replace line breaks * , not just \n , is best to use:

>>> "Quebra de linha *nix.\nQuebra de linha Mac.\rQuebra de linha Windows.\r\n".replace(/\r\n|[\r\n]/g, '<br />');
"Quebra de linha *nix.<br />Quebra de linha Mac.<br />Quebra de linha Windows.<br />"

* There are two other types of line breaks besides the * nix style ( \n ): \r (old Mac style) and \r\n (Windows style). >     

12.12.2013 / 14:48
3

To replace with <br/> , do:

result = result.replace(/\n/g, "<br/>");

To replace with <p>...</p> :

result = "<p>" + result.replace(/\n/g, "</p><p>") + "</p>";

The best approach depends on what you want, but I would go for the <p> tag because you could format with CSS and handle it more easily with javascript.

    
12.12.2013 / 13:57
0

Using the methods split and join also comes up with the result:

>>> "Primeiro parágrafo.\nSegundo parágrafo.".split('\n').join('<br/>');
"Primeiro parágrafo.<br/>Segundo parágrafo."

let res = "Primeiro parágrafo.\nSegundo parágrafo.".split('\n').join('<br/>');
document.querySelector('#resultado').innerHTML = res;
<div id="resultado"></div>
    
27.05.2018 / 05:00
-5

Using regular expression is possible this way:

str = str.replaceAll("(\r\n|\n)", "<br />");
    
12.12.2013 / 13:56