美文网首页markdown
758. 【前端】从markdown格式文本中提取图片链接

758. 【前端】从markdown格式文本中提取图片链接

作者: 七镜 | 来源:发表于2023-08-10 23:33 被阅读0次

    分享一个前端工具函数,从markdown格式文本中提取图片链接,
    回家上干货:

    function markdownFindImageLinkFirst(markdown:string,defaultLink:string):string{
    
        const regex = /\!\[.*\]\(http.*\)/g;
    
        const matches = markdown.match(regex);
    
        if(matches == null) {
            return  defaultLink;
        }
        const firstMatch = matches[0];
    
    // 使用replace方法,将不需要的部分替换为空字符串,得到纯净的图片链接
        const firstImageLink = firstMatch.replace(/\!\[.*\]|\(|\)/g, '');
    
        return firstImageLink
    }
    

    其实,可以看到只是写了两个正则表达式而已,但却能切实解决从markdown中提取第一张图片链接的问题,该功能将支持新闻列表页概览功能的开发。

    有时候没必要使用多么复杂的技术,能解决实际需求就好。

    相关文章

      网友评论

        本文标题:758. 【前端】从markdown格式文本中提取图片链接

        本文链接:https://www.haomeiwen.com/subject/upripdtx.html