-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse-headings.js
52 lines (46 loc) · 1.47 KB
/
parse-headings.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
52
const fs = require('fs');
// read theme color from _data/site.json
fs.readdir('./content/dil-mil/', 'utf8', function (err, files) {
if (err) {
console.log(err);
return;
}
for (let i = 0; i < files.length; i++) {
const file = files[i];
fs.readFile(
`./content/dil-mil/${file}`,
'utf8',
function (err, fileContents) {
if (err) {
console.log(err);
return;
}
const iteration = i + 1;
const headerStringUntrimmed = fileContents.split('<h2>')[iteration];
const headerStringDirty = headerStringUntrimmed?.split('</h2>')[0];
const headerString = headerStringDirty
?.replaceAll('</span>', '')
.replaceAll('<span>', '');
const headerStringSlug = headerStringDirty
?.toLowerCase()
.replaceAll(' ', '-')
.replaceAll(/[?.]/g, '')
.replaceAll('</span>', '')
.replaceAll('<span>', '')
.replaceAll(/[0-9]/g, '');
const stringToReplace = '<h2>' + headerStringDirty + '</h2>';
const newFileContents = fileContents.replace(
stringToReplace,
`<h2 id="${headerStringSlug}"><a href="#${headerStringSlug}">${headerString}</a></h2>`
);
fs.writeFile(`./content/dil-mil/${file}`, newFileContents, (err) => {
if (err) {
console.log(err);
return;
}
console.log(`Successfully wrote ${file}`);
});
}
);
}
});