我发现这个问题很有趣,所以我决定开始尝试(只替换 strong
和 italic
markdown 标签)。花了一个小时尝试使用正则表达式来设计一个解决方案后,我放弃了,并得到了以下解决方案,它似乎运行良好。话虽如此,它肯定可以进一步优化,而且我不确定它在这种形式下有多少真实世界的弹性:
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
编辑:V0.024新增 - 自动删除未闭合的Markdown标签