编辑代码

// 使用示例
const markdown = `
- Item 1
- Item 2
  - Subitem 2a
  - Subitem 2b
- Item 3
`;

const t = parseUl(markdown)

console.log("parse t:",t)
function parseUl(markdown)
{
    let currentLevel = 0;
    let tHtml = '';
    let tStr = markdown;
    const lines = tStr.split('\n');
    const matchRegex = /^(\s*)- (.*)/; // 匹配列表项
    for(let line of lines)
    {
        if(!line)
        {
            continue;
        }
        const tMatch = line.match(matchRegex);
        //console.log('t match:', tMatch);
        if(tMatch)
        {
            const level = tMatch[1].length / 2; // 计算当前行的缩进级别
            console.log('t level:', level);
            const tText = line.repalaceAll(/^(\s*)- /, '')
            if(level == currentLevel)
            {
                tHtml += `<li>${tText}</li>`;
            }
            else if(level > currentLevel) // 子层级
            {
                tHtml += `<ul>`;
                tHtml += `<li>${tText}</li>`;
                
            }
            else if(level < currentLevel)
            {
                tHtml += `<li>${tText}</li>`
                for(let i = 0; i < currentLevel - level; i++)
                {
                    tHtml += '</ul>'
                }
            }
            currentLevel = level;
        }
        
    }
    
    
    return tHtml
}