html5中diouas作用,将Markdown/Textile转换为HTML的Javascript(理想情况下,返回Markdown/Textile)...

本文介绍了一种将Markdown格式文本转换为HTML的方法,通过编写JavaScript函数实现了对加粗和斜体文本标记的有效转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我发现这个问题很有趣,所以我决定开始一些事情(只替换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中的新功能 - 自动删除未闭合的降价标签

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值