我有一个使用Github's markdown格式化的changelog文件。
最初,我将内联链接用于需要添加的每个链接,即:
This is some [example](http://www.stackoverflow.com) line of text.
随着时间的流逝,随着文件大小的增加,主要由于这种插入链接的方式使文件变得有些困惑。
我想将所有链接从内联转换为引用(请参阅description of each),即将上面的行转换为此:
This is some [example][1] line of text.
[1]: http://www.stackoverflow.com
由于该文件很大,并且包含许多内联链接,所以我想知道是否存在一些自动方法来执行此操作。我使用Sublime Text 3进行编辑,但找不到适合此任务的软件包。也许一些聪明的正则表达式?
最佳答案
这是一个很大的要求!
我刚刚创建了一个新的Node.js程序(我知道它不是GUI,但似乎更多的人希望此功能)在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);
});
});
关于regex - 将Markdown链接从内联转换为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30917399/