【发布时间】:2021-12-29 19:15:59
【问题描述】:
我正在尝试将 markdown 样式的内容解析为 HTML 内容。
例如[test](https://test.com) --> <a href="https://test.com">test</a>
要将超链接变成锚标签,我有这样的说法:
.replace(/\[([^\[]+)\](\(([^)]*))/gim, '<a href="$3">$1</a>');
目前,这个正则表达式接受[test](https://test.com) 作为输入,但它无法匹配整个字符串——它只能识别[test](https://test.com。所以它会输出带有尾括号的<a href="https://test.com">test</a>)。
有人可以帮我修复上面的语句,以便它可以使用 markdown 链接并按预期呈现锚标签吗?对于文档,这是进行此转换的完整功能:
const markdown = `[test](https://test.com)`
const html = markdown.replace(/^### (.*$)/gim, '<h3>$1</h3>') // h3 tag
.replace(/^## (.*$)/gim, '<h2>$1</h2>') // h2 tag
.replace(/^# (.*$)/gim, '<h1>$1</h1>') // h1 tag
.replace(/\*\*(.*)\*\*/gim, '<b>$1</b>') // bold text
.replace(/\*(.*)\*/gim, '<i>$1</i>') // italic text
.replace(/\r\n|\r|\n/gim, '<br>') // linebreaks
.replace(/\[([^\[]+)\](\(([^)]*))/gim, '<a href="$3">$1</a>'); // anchor tags
console.log(html)
【问题讨论】:
-
我用
[<>]sn-p 编辑器给你做了一个minimal reproducible example - 当问题可以用普通的JS显示时,不需要在这里显示苗条
标签: javascript regex replace markdown