#ActuallyAutistic web dev. Does front of the front-end. Loves perf and minimalism. Prefers HTML, CSS, Web Standards over JS, UX over DX. Hates div disease.
However this smells from HTML / CSS perspective because we're generating HTML like this:
<h1>Hello World</h1><br/><p>Why there is a line break between paragraphs?</p><br/><p>Did someone set paragraph margins to zero? That is evil business!</p><br/><br/><br/><br/><br/><p>OMG I can do formatting with line breaks. Woohoo.</p>
While it works it is "ugly", and giving users the power to do as many line breaks as possible isn't often really desired. So we could only separate paragraphs when we have multiple line breaks in the source text.
constdocument=text.trim()// try this out at https://regex101.com.split(/\n\s*\n/).map((line)=>line.replace(/\n/g,'<br />')).map((line,index)=>index===0?`<h1>${line}</h1>`:`<p>${line}</p>`).join('\n')
And now we get "nicer" HTML output:
<h1>Hello world!</h1><p>I can no longer have multiple line breaks between paragraphs.</p><p>However I can...<br/>now...<br/>have...<br/>line breaks...<br/>within paragraphs! (And the header too.)</p><p>And paragraphs can retain their margins in CSS like they should when normal text is concerned.</p>
But this isn't good either, because this is still a non-standard way of parsing text to HTML. To have confidence you should make extensive tests to cover possible edge cases, and you have to maintain it yourself. So what to do?
Just use Markdown.
It might be worth the pain to refactor to using some Markdown library. Don't write your own, by now there are plenty of options that fit about any use case imaginable.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Well there are certainly more problems with this than just this function. For example we don't know if the line data has been escaped properly.
So if we go a bit outside the box of the function, and we keep the logic we could generate the document like this:
However this smells from HTML / CSS perspective because we're generating HTML like this:
While it works it is "ugly", and giving users the power to do as many line breaks as possible isn't often really desired. So we could only separate paragraphs when we have multiple line breaks in the source text.
And now we get "nicer" HTML output:
But this isn't good either, because this is still a non-standard way of parsing text to HTML. To have confidence you should make extensive tests to cover possible edge cases, and you have to maintain it yourself. So what to do?
Just use Markdown.
It might be worth the pain to refactor to using some Markdown library. Don't write your own, by now there are plenty of options that fit about any use case imaginable.