-
Notifications
You must be signed in to change notification settings - Fork 7
/
nGitHubTOC.js
51 lines (41 loc) · 1.53 KB
/
nGitHubTOC.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function tocIt(inputMD, minHeading, maxHeading, ignoreLinex)
{
if(minHeading > maxHeading) return;
inputMDLines = inputMD.split("\n");
var outputMD = "";
var anchorTracker = {};
var codeTagEndExpected = false;
for(var i = 0; i < inputMDLines.length; ++i)
{
var inputMDLine = inputMDLines[i].trim();
var codeTag = /^.*(`{3}) ?(.*)?$/.exec(inputMDLine);
if(codeTag)
{
codeTagEndExpected = !codeTagEndExpected;
continue;
}
var match = /^(#+) (.*)$/.exec(inputMDLine);
if(!codeTagEndExpected && match)
{
var headingLevel = match[1].length;
var headingTitle = match[2].replace(/<.*?>/g, "");
if(headingLevel < minHeading || headingLevel > maxHeading)
{
continue;
}
headingLevel -= minHeading;
var headingAnchor = headingTitle.toLowerCase().replace(/[^_*0-9a-z\xE0-\xFF- ]/g, "").replace(/_{1,2}(.+?)_{1,2}/g, "$1").replace(/\*{1,3}(.+?)\*{1,3}/g, "$1").replace(/ /g, "-");
if(headingAnchor in anchorTracker)
{
anchorTracker[headingAnchor]++;
headingAnchor = headingAnchor + "-" + anchorTracker[headingAnchor];
}
else
{
anchorTracker[headingAnchor] = 0;
}
outputMD += " ".repeat(headingLevel * 2) + "- [" + headingTitle + "](#" + headingAnchor + ")\n";
}
}
return outputMD;
}