DEV Community

Discussion on: How would you refactor this JS function?

Collapse
 
merri profile image
Vesa Piittinen • Edited

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:

const document = text
  .trim()
  .split('\n')
  .map((line, index) =>
    (line === '' && '<br />') ||
    (index === 0 && `<h1>${line}</h1>`) ||
    `<p>${line}</p>`
  )
  .join('\n')
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.

const document = 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')
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.