且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将Markdown链接从内联转换为参考

更新时间:2023-02-23 13:07:14

这是一个很好的要求!

我刚刚创建了一个新的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);
    });

});