【问题标题】:How can we parse markdown hyperlinks into html anchor tags我们如何将markdown超链接解析为html锚标签
【发布时间】: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)

【问题讨论】:

  • 我用[&lt;&gt;] sn-p 编辑器给你做了一个minimal reproducible example - 当问题可以用普通的JS显示时,不需要在这里显示苗条

标签: javascript regex replace markdown


【解决方案1】:

你刚刚错过了\)

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)

【讨论】:

    【解决方案2】:

    不应该比这复杂得多:

    https://regex101.com/r/wKvNuy/1

    const rxCommonMarkLink = /(\[([^\]]+)])\(([^)]+)\)/g;
    
    function commonMarkLinkToAnchorTag(md) {
      const anchor = md
        ? md.replace( rxCommonMarkLink , '<a href="$3"> $2 </a>' )
        : md
        ;
    }
    

    但实际上,您不应该只使用适当的解析器吗?

    备注建立在:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多