将Markdown链接从内联转换为参考 [英] Convert markdown links from inline to reference

查看:212
本文介绍了将Markdown链接从内联转换为参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Github的markdown 格式化的变更日志文件.

I have a changelog file formatted using Github's markdown.

最初,我将 inline 链接用于我需要添加的每个链接,即:

Initially I used inline links for every link I needed to add, that is:

This is some [example](http://www.stackoverflow.com) line of text.

随着时间的流逝,随着文件大小的增加,它变得有点杂乱,主要是因为这种插入链接的方式.

Over time, as the file grew in size, it became a bit messy due mainly to this way of inserting links.

我想将所有链接从内联转换为引用(请参阅每个链接的描述),即将上面的行转换为此:

I'd like to convert all links from inline to reference (see description of each), that is convert the above line to this:

This is some [example][1] line of text.

[1]: http://www.stackoverflow.com

由于该文件很大,并且包含许多 inline 链接,所以我想知道是否存在某种自动方式来执行此操作.我使用Sublime Text 3进行编辑,但找不到适合此任务的软件包.也许一些聪明的正则表达式?

Since the file is rather large and contains many inline links, I was wondering if there is some automated way to do this. I use Sublime Text 3 to edit, but I couldn't find a suitable package for this task. Perhaps some clever regex?

推荐答案

这是一个很好的要求!

我刚刚创建了一个新的Node.js程序(我知道它不是GUI,但似乎更多的人希望它具有这种功能)可以在

I've just created a new Node.js program (I know it's not a GUI but seems something more people would like the capability of) to do this on GitHub.

这也是代码:

// node main.js test.md result.md

var fs = require('fs')
fs.readFile(process.argv[2], 'utf8', function (err, markdown) {
    if (err) {
        return console.log(err);
    }
    var counter = 1;
    var matches = {};
    var matcher = /\[.*?\]\((.*?)\)/g;
    while (match = matcher.exec(markdown)) {
        if (!matches[match[1]]) matches[match[1]] = counter++;
    }
    console.log(matches);
    Object.keys(matches).forEach(function(url) {
        var r = new RegExp("(\\[.*?\\])\\(" + url + "\\)", "g");
        markdown = markdown.replace(r, "$1[" + matches[url] + "]");
        markdown += "\n[" + matches[url] + "]: " + url;
    });

    fs.writeFile(process.argv[3], markdown, 'utf8', function (err) {
        if (err) return console.log(err);
    });

});

这篇关于将Markdown链接从内联转换为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆