如何从 Markdown 在 JavaScript 中创建目录解析器?

问题描述 投票:0回答:2

降价

# Rahul
The community is here to help you with specific coding, algorithm, or language problems.The community is here to help you with specific coding, algorithm, or language problems.

## This is second heading
The community is here to help you with specific coding, algorithm, or language problems.

### This is third heading
The community is here to help you with specific coding, algorithm, or language problems.The community is here to help you with specific coding, algorithm, or language problems.

## This is fourth heading.

所需输出

<ol>
    <li>Rahul</li>
    <ol>
        <li>This is second heading</li>
        <ol>
            <li>This is third heading</li>
        </ol>
        <li>This is fourth heading</li>
    </ol>
</ol>

我也通过互联网和stackoverflow进行了搜索,但我无法获得任何有用的信息,没有好的学习资源等等。

感谢您的帮助

javascript parsing markdown
2个回答
0
投票

为了帮助您入门,这里有一个用于提取标题的快速正则表达式技术。

markdown = `# Rahul
The community is here to help you with specific coding, algorithm, or language problems.The community is here to help you with specific coding, algorithm, or language problems.

## This is second heading
The community is here to help you with specific coding, algorithm, or language problems.

### This is third heading
The community is here to help you with specific coding, algorithm, or language problems.The community is here to help you with specific coding, algorithm, or language problems.

## This is fourth heading.`;

headings = ( markdown + '\n').match(/(#+ .*\n)/g);
console.log( headings )

接下来的步骤将涉及遍历列表,并确定......

  • 如果下一个标题有更多 #,则添加
    <ol>
    's
  • 或者如果下一个标题的 # 较少,则添加
    </ol>

请注意,如果下一个标题下降,例如从 3 # 下降到 1 #,则需要添加 2 个

</ol>


0
投票

嗯,这是一个有趣的练习。我的代码太长,无法发布,但您可以在这里查看。.

本质上:

我创建了一个 4 层深的示例 Markdown 文本。

将其转换为 html。

将 html 导入到临时 DOM 中。

使用

getElementsBy
方法之一收集临时文档中的所有标题。 为了维护
h*
元素的文档顺序,我将它们及其文本节点推入两个数组中。

下一步有时会被一些人非常不赞成,他们认为这是一种不好的编程习惯,但我已经使用它很多次了,没有任何问题,并且发现它比替代方案更容易处理:通过迭代创建一个新的 html 字符串数组并用必要标签的适当字符串表示形式包围每个元素。

最后,将标签导入到主 DOM 中。

它可能不是 100% 满足您的需求,但应该可以让您接近。

© www.soinside.com 2019 - 2024. All rights reserved.