这次蓝桥杯看到第九题的时候直接跳过了,没有细看题目的具体要求,今天突然心血来潮想再看一下这个markdown解析的题目,然后试着给出一下自己的解法,以下只是我的简单实现,并没有再去考虑更复杂的情况,只考虑题目中的情况,可能不具备通用性,同时这也是我的第一篇文章,可能写的也不够严谨,所以还请各位大佬指正,不胜感激。题目是由网上找的,很感谢网友提供的题目!!!
首先解析分隔符hr标签
Parser类中
// TODO: 补充分割符正则
this.hr = /-{3,}/g
//判断是否为hr
isHr() {
return this.hr.test(this.lineText)
}
// 解析分隔符
parseHr() {
return `<hr />`
}
接着开始正式生成
Reader类中
if (this.parser.isHr()) {
hasParsed.push(this.parser.parseHr());
currentLine++;
continue;
}
对引⽤区块进⾏解析
我的思路是如果检测到引用区块的话,就要先生成<blockquote>开始标签,随后对里面的内容生成p标签,当引用区块结束时(也就是下一行不为引用区块),那么就生成</blockquote>结束标签
Parser类中
// 判断是否为blockQuote
isBlockQuote(){
return this.blockQuote.test(this.lineText)
}
// 解析blockQuote开始标签
parseStartBlockQuote(){
return `<blockquote>`
}
// 解析blockQuote结束标签
parseEndBlockQuote(){
return `</blockquote>`
}
// 生成blockQuote中的p标签
parseBlockQuoteP(){
const temp = this.lineText.split(">")
const content = temp[1].trim()
return `<p>${content}</p>`
}
Reader类中
if (this.parser.isBlockQuote()){
hasParsed.push(this.parser.parseStartBlockQuote())
while(true){
if(this.reachToEndLine(currentLine)){
hasParsed.push(this.parser.parseEndBlockQuote())
break
}
hasParsed.push(this.parser.parseBlockQuoteP())
currentLine++;
this.parser.parseLineText(this.getLineText(currentLine));
if(!this.parser.isBlockQuote()){
hasParsed.push(this.parser.parseEndBlockQuote())
break
}
}
continue;
}
对无序列表进行解析<