gpt4 book ai didi

javascript - 解析 Markdown 标题以在 JavaScript 中生成嵌套列表

转载 作者:行者123 更新时间:2023-11-29 23:48:28 25 4
gpt4 key购买 nike

我一直在尝试根据“#”的数量来嵌套标题。我解析了 markdown 并提取了所有标题。它们的格式如下

# Getting Started
# Heading 1
## SubHeading 1
## SubHeading 2
### SubSubHeading 1
### SubSubHeading 2
#### SubSubSubHeading 1
## SubHeading 3

我试图递归地将它转换为嵌套的 ul 列表,但它似乎不起作用。这就是我到目前为止所做的

function createRepresentationFromHeadings(headings, index, level) {
var data = "<ul>";
for (var i = index; i < headings.length; i++) {
var heading = headings[i];
var parts = heading.split("# ");
parts[0] = parts[0] + "#";
data += "<li>" + parts[1];
if (i + 1 < headings.length) {
var nextParts = headings[i + 1].split("# ");
nextParts[0] = nextParts[0] + "#";
if (determineHeadingLevel(nextParts[0]) > level)
createRepresentationFromHeadings(headings, i + 1, determineHeadingLevel(nextParts[0]));
}
data += "</li>";
}
data += "</ul>";
return data;
}

function determineHeadingLevel(part) {
return part.length;
}

它只是创建了一个扁平化的 ul。这是一个 fiddle :https://jsfiddle.net/vrt2889q/

最佳答案

您可以使用这个递归(子)函数:

function createRepresentationFromHeadings(headings) {
let i = 0;
const tags = [];

(function recurse(depth) {
let unclosedLi = false;
while (i < headings.length) {
const [hashes, data] = headings[i].split("# ");
if (hashes.length < depth) {
break;
} else if (hashes.length === depth) {
if (unclosedLi) tags.push('</li>');
unclosedLi = true;
tags.push('<li>', data);
i++;
} else {
tags.push('<ul>');
recurse(depth+1);
tags.push('</ul>');
}
}
if (unclosedLi) tags.push('</li>');
})(-1);
return tags.join('\n');
}

var headings = [
"# Getting Started",
"# Heading 1",
"## SubHeading 1",
"## SubHeading 2",
"### SubSubHeading 1",
"### SubSubHeading 2",
"#### SubSubSubHeading 1",
"## SubHeading 3",
];

document.getElementById("test").innerHTML =
createRepresentationFromHeadings(headings);
<div id="test"></div>

关于javascript - 解析 Markdown 标题以在 JavaScript 中生成嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43356176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com