我发现这个问题很有趣,所以我决定开始一些事情(只替换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 = '' + innerTxt + '';
tempStr = tempStr.substring(0,firstPos) + strongified + tempStr.substring(nextPos + 2,tempStr.length);
//get rid of unclosed '**'
} 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 = '' + innerTxt + '';
tempStr = tempStr.substring(0,firstPos) + italicized + tempStr.substring(nextPos + 2,tempStr.length);
//get rid of unclosed '*'
} 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 italicizedtext and this would be bold text, This would be italicizedtext and this would be bold text, This would be italicizedtext and this would be bold text编辑:V 0.024中的新功能 - 自动删除未闭合的降价标签