使用JavaScript将纯文本列表转换为HTML列表

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

我经常收到PDF格式的文本列表,这些列表是分层的(通常是三层)。我想将它们放入HTML列表中,以便可以使用CSS设置样式并使其更具表现力。由于数据量大,我正在尝试使用JavaScript自动化该过程。

示例源数据:

・First Level 1 list item
– First Level 2 list item, which is a subset of the first Level 1 list item.
– Second Level 2 list item, which is a subset of the first Level 1 list item.
♦ First Level 3 list item, which is a subset of the second Level 2 list item.
・Second Level 1 list item.

示例目标:

<ul>
    <li>First Level 1 list item</li>
        <ul>
            <li>First Level 2 list item, which is a subset of the first Level 1 list item.</li>
            <li>Second Level 2 list item, which is a subset of the first Level 1 list item.
                <ul>
                    <li>First Level 3 list item, which is a subset of the second Level 2 list item.</li>
                </ul>
            </li>
        </ul>
    <li>Second Level 1 list item.</li>
</ul>

到目前为止的进展:

我确定我可以使用此正则表达式匹配1级列表项:/^・.+$/gm

并使用此正则表达式匹配2级列表项:/^\–.+$/gm

以及第3级:/^♦.+$/gm

或者简单地通过组合以下列表来立即划定列表级别的allstring.match(/(^・.+$)|(^\–.+$)|(^♦.+$)/gm);

现在知道如何匹配不同类型的项目,我试图弄清楚如何对它们进行排序。从概念上讲,如果我将它们全部放在一个数组中(让我们在下一个示例中使用简单的颜色编码),那么应该可以创建一个可以识别模式并在正确的层次结构中创建多维数组的函数,然后是另一个函数,用于在适当位置输出用HTML标记填充的内容。

基于类型的将一维数组转换为多维数组的可视化:

假设在上面的简化示例中,我们只有三个字母的字符串对应于颜色-rgb

所以可能看起来像:rrgbrgbrgbbrggbr

我一直在尝试并尝试将这种结构转换为多维数组。

我相信,需要3级以下的维度来保存实际的文本字符串。并且需要高于1级的一个维度来涵盖每个完整列表。所以这样的结构:

list
[
    level1
    [
        level2
        [
            level3
            [   
                string
                ["list item text"]
            ]
        ]
    ]
]

在这里,我很难弄清楚如何对所有这些进行排序。任何帮助表示赞赏。

javascript arrays sorting multidimensional-array html-lists
1个回答
0
投票

不需要正则表达式。

var log = console.log;
var data = `・First Level 1 list item
– First Level 2 list item, which is a subset of the first Level 1 list item.
– Second Level 2 list item, which is a subset of the first Level 1 list item.
♦ First Level 3 list item, which is a subset of the second Level 2 list item.
・Second Level 1 list item.`;
data = data.split("\n");
var firstChar,prevFirstChar = "";
var struct = [];
var cursor = struct;
var lvl1Key = "・";
var prevnode = {};

data.forEach(line=>{
    firstChar = line.charAt(0);
    let node = {
        str : line.slice(1),
        child : []
    };
    if (firstChar == lvl1Key) {
      cursor = struct;
    } else if (firstChar != prevFirstChar) {
      cursor = prevnode.child;
    }
    cursor.push(node);
    prevnode = node;
    prevFirstChar = firstChar;
});
log(struct);

const offsetSize = 2;
var toHtml = function(node, offset = "") {
    var ret = offset + "<ul>\n";
    offset += " ".repeat(offsetSize);
    node.forEach(rec=>{
        ret += offset + "<li>" + rec.str + "</li>\n";
        if (rec.child.length) {
            ret += toHtml(rec.child, offset + " ".repeat(offsetSize));
        }
    });
    offset = offset.slice(offsetSize);
    ret += offset + "</ul>\n";
    return ret;
}
log(toHtml(struct));
© www.soinside.com 2019 - 2024. All rights reserved.