javascript – 需要帮助解析markdown,删除斜体(*)但不是粗体(**)

我正在尝试复制WMD Markdown Editor.我试图修改WMD而不是重新发明轮子,但它的代码对我来说是不可读的……

所以我试图删除斜体“*”而不是粗体“**”

因此,应删除下面的斜体

this *is a* test
this ***is a*** test

但下面的内容应该不受影响

this **is a** test

我想我应该使用RegExp但是怎么样?如果*仅在“单独”或者后面跟着2或更多* s时我如何匹配*

最佳答案 直接正则表达式很难解决这个问题,特别是处理星号位于字符串开头或结尾的边缘情况.将一些正则表达式魔法与一些替换魔法相结合可以完成工作……

function removeItalics(str) {
    var re = /\*+/g;
    return str.replace(re, function(match, index) { return match.length === 2 ? '**' : ''; });
}

alert(removeItalics("this *is a* test"));     // this is a test
alert(removeItalics("this **is a** test"));   // this **is a** test
alert(removeItalics("this ***is a*** test")); // this is a test

我们匹配一个或多个星号的运行.比赛很贪婪.因此,最长的星号将匹配.如果匹配的长度是2,我们将星号放回去,否则我们将它们剥离.

工作示例如下:http://jsfiddle.net/QKNam/

更新:如果您想要保留加粗,如果您有2个或更多星号,只需更改match.length逻辑,如下所示…

function removeItalics(str) {
    var re = /\*+/g;
    return str.replace(re, function(match, index) { return match.length === 1 ? '' : '**'; });
}

alert(removeItalics("this *is a* test"));     // this is a test
alert(removeItalics("this **is a** test"));   // this **is a** test
alert(removeItalics("this ***is a*** test")); // this **is a** test

更新了jsFiddle:http://jsfiddle.net/QKNam/3/

点赞