JavaScript For、函数和混合返回

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

我正在创建我自己的

MarkDown
渲染版本。我的目标是逐行读取字符串或文件,然后返回渲染为
MD
HTML
。我面临的问题是我的返回和逐行功能没有返回我想要的东西,我不知道为什么。我尝试过调试,但一切似乎都很好。我也尝试过改变我的 for 循环,但仍然没有运气。

//function used to render MD for the user

function render(md){
    let code = ""; //For functions return

    let mdLines = md.split('\n');

    for(let i = 0; i < mdLines.length; i++){

        //Statements to see what kind of MD header a line is.
        //I only have these statments as I just started this and am still figuring how I want to approach.

        if(mdLines[i].slice(0, 1) == "#"){
           code += code.concat("<h1>" + mdLines[i].replace("#", "") + "</h1>")
        }

        if(mdLines[i].slice(0, 2) == "##"){
           code += code.concat("<h2>" + mdLines[i].replace("##", "") + "</h2>")
        }

        if(mdLines[i].slice(0, 3) == "###"){
           code += code.concat("<h3>" + mdLines[i].replace("###", "") + "</h3>")
        }

        if(mdLines[i].slice(0, 4) == "####"){
           code += code.concat("<h4>" + mdLines[i].replace("#", "") + "</h4>")
        }

        if(mdLines[i].slice(0, 5) == "#####"){
           code += code.concat("<h5>" + mdLines[i].replace("#", "") + "</h5>")
        }

        if(mdLines[i].slice(0, 6) == "######"){
           code += code.concat("<h6>" + mdLines[i].replace("######", "") + "</h6>")
        }
    };
    
    return code;
}


//editor
//This is what the users .js file would be.
//I have it set up like this for testing.

let text1 = "## he#llo \n there \n # yooo"
let text2 = "# he#llo \n there \n ## yooo"

console.log(render(text1));
console.log(render(text2));

text1 返回

<h1># he#llo </h1><h1># he#llo </h1><h2> he#llo </h2>
text2 返回
<h1> he#llo </h1>

text1 应该返回

<h2>he#llo</h2> there <h1> yooo </h1>
text2 应该返回
<h1> he#llo </h1> there <h2> yooo </h2>

如果有人可以帮助我获得适当的回报和一些可能可重用的代码来解决这个问题,我将不胜感激。

我还使用一些选定的术语查找了该问题,但似乎没有人记录了我的非常具体的问题。

javascript html markdown renderer
1个回答
0
投票

这里有一个更好、更通用的方法来处理这个问题。此外,它不会像您的那样删除字符串中间的“#”。这依赖于 ### 标头后面必须跟有空格的事实。

function render(md){
    let code = "";

    let mdLines = md.split('\n');

    for(let i = 0; i < mdLines.length; i++){
        
        if(mdLines[i][0] == "#") {
            // We have a header.  How many are there?
            let s = mdLines[i].indexOf(" ")
            if( mdLines[i].slice(0,s) == '#'.repeat(s) )
                code += "<h"+s+">" + mdLines[i].slice(s+1) + "</h"+s+">";
            else
                code += mdLines[i];
        }
        else
            code += mdLines[i];
    };
    
    return code;
}

let text1 = "## he#llo \n there \n # yooo"
let text2 = "# he#llo \n there \n ## yooo"

console.log(render(text1));
console.log(render(text2));

输出:

timr@Tims-NUC:~/src$ node x.js
<h2>he#llo </h2> there  # yooo
<h1>he#llo </h1> there  ## yooo

timr@Tims-NUC:~/src$
© www.soinside.com 2019 - 2024. All rights reserved.