Remark or Rehype Plugin to convert newlines(\n) to </br>

795 Views Asked by At

I have a markdown document and I am using rehype and remark to convert it into html. The problem am facing is that, inside my markdown file, I have some (\ns) which I want to be converted into <br/> tags in HTML but I do not know how to do it. Also, there is no plugin which solves this problem.

1

There are 1 best solutions below

0
shtse8 On

remark-rehype won't convert newline to <br />. It only convert to:

{
    "type": "text",
    "value": "\n",
    "position": {
        "start": {
            "line": 1,
            "column": 65,
            "offset": 64
        },
        "end": {
            "line": 2,
            "column": 1,
            "offset": 65
        }
    }
}

If you want to convert \n to <br />, you need to modify the tree by replacing \n to <br /> in text node using visit.

npm install remark remark-html unist-util-visit
const remark = require('remark');
const remark2rehype = require('remark-rehype');
const unified = require('unified');
const rehypeStringify = require('rehype-stringify');
const visit = require('unist-util-visit');
const u = require('unist-builder');

// Custom plugin to convert newlines in text to `br` element nodes
const remarkNewlinesToBrs = () => tree => {
  visit(tree, 'text', (node, index, parent) => {
    if (node.value.includes('\n')) {
      // Split the text at newlines
      const parts = node.value.split('\n');
      const newNodes = [];
      parts.forEach((part, i) => {
        if (part !== '') {
          // Add text node for the non-empty part
          newNodes.push(u('text', part));
        }
        if (i !== parts.length - 1) {
          // Add a `br` element node for each newline, except after the last part
          newNodes.push(u('element', {tagName: 'br'}, []));
        }
      });
      // Replace the current text node with the new nodes
      parent.children.splice(index, 1, ...newNodes);
    }
  });
};

// Example Markdown
const markdown = 'This is a test.\nThis should be on a new line.';

// Process the Markdown
unified()
  .use(remark)
  .use(remarkNewlinesToBrs) // Use the custom plugin
  .use(remark2rehype, {allowDangerousHtml: true})
  .use(rehypeStringify)
  .process(markdown, (err, file) => {
    if (err) throw err;
    console.log(String(file));
  });