我发现这个问题很吸引人,所以我决定从头开始(仅替换strong
和italic
降价标记)。花了一个小时尝试使用正则表达式设计解决方案后,我放弃了并最终获得了以下内容,该方法似乎运行良好。就是说,它肯定可以进一步优化,但我不确定这种形式在现实世界中的弹性如何:
function mdToHtml(str) {
var tempStr = str;
while(tempStr.indexOf("**") !== -1) {
var firstPos = tempStr.indexOf("**");
var nextPos = tempStr.indexOf("**",firstPos + 2);
if(nextPos !== -1) {
var innerTxt = tempStr.substring(firstPos + 2,nextPos);
var strongified = '<strong>' + innerTxt + '</strong>';
tempStr = tempStr.substring(0,firstPos) + strongified + tempStr.substring(nextPos + 2,tempStr.length);
} else {
tempStr = tempStr.replace('**','');
}
}
while(tempStr.indexOf("*") !== -1) {
var firstPos = tempStr.indexOf("*");
var nextPos = tempStr.indexOf("*",firstPos + 1);
if(nextPos !== -1) {
var innerTxt = tempStr.substring(firstPos + 1,nextPos);
var italicized = '<i>' + innerTxt + '</i>';
tempStr = tempStr.substring(0,firstPos) + italicized + tempStr.substring(nextPos + 2,tempStr.length);
} else {
tempStr = tempStr.replace('*','');
}
}
return tempStr;
}
测试代码:
var s = "This would be *italicized* text and this would be **bold** text, This would be *italicized* text and this would be **bold** text, This would be *italicized* text and this would be **bold** text";
alert(mdToHtml(s));
输出:
This would be <i>italicized</i>text and this would be <strong>bold</strong> text, This would be <i>italicized</i>text and this would be <strong>bold</strong> text, This would be <i>italicized</i>text and this would be <strong>bold</strong> text
编辑:V 0.024中的新增功能-自动删除未关闭的降价标签