【问题标题】:Regex to convert markdown to html正则表达式将 Markdown 转换为 html
【发布时间】:2022-10-04 16:39:38
【问题描述】:
我的目标是获取降价文本并创建必要的粗体/斜体/下划线 html 标签。
环顾四周寻找答案,得到了一些灵感,但我仍然卡住了。
我有以下打字稿代码,正则表达式匹配包括双星号的表达式:
var text = 'My **bold\n\n** text.\n'
var bold = /(?=\*\*)((.|\n)*)(?<=\*\*)/gm
var html = text.replace(bold, '<strong>$1</strong>');
console.log(html)
现在的结果是:我的 <\strong>** 粗体\n\n **<\strong> 文本。
除了剩下的双星号外,一切都很棒。
我还尝试在稍后的“替换”语句中删除它们,但这会产生更多问题。
我怎样才能确保它们被正确删除?
【问题讨论】:
-
您是否有任何理由不使用许多现有的降价库之一,例如Marked?
标签:
javascript
regex
typescript
regexp-replace
【解决方案1】:
只需再次调用replaceAll 删除带有空字符串的**。
var text = 'My **bold
** text.
'
var bold = /(?=**)((.|
)*)(?<=**)/gm
var html = text.replace(bold, '<strong>$1</strong>');
html = html.replaceAll(/**/gm,'');
console.log(html)
【解决方案2】:
基于 Koen Vendrik 的 CodePen Home JavaScript Markdown Parser,您可以使用以下正则表达式:/[*_]{2}([^*_]+)[*_]{2}/g
var text = 'My **bold
** text.
'
var bold = /[*_]{2}([^*_]+)[*_]{2}/g
var html = text.replace(bold, '<strong>$1</strong>');
console.log(html)
【解决方案3】:
用你的图案(?=**)((.|
)*)(?<=**)你断言(不匹配)与(?=**) 直接在右侧有**。
然后直接在那之后,你捕获** 使用 ((.|
)*) 所以它成为比赛的一部分。
然后最后你断言再次使用(?<=**),即左侧直接有**,但((.|
)*) 已经匹配了它。
这样一来,您将在比赛中得到所有 **。
您根本不需要环顾四周,因为您已经在使用捕获组。
在 Javascript 中,您可以编写:
**([^]*?)**
Regex demo
但我建议使用专用解析器来解析降价而不是使用正则表达式。