-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
58 lines (49 loc) · 1.68 KB
/
index.ts
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
53
54
55
56
57
58
import fs from "fs";
export interface Heading {
id: number;
slug: string;
title: string;
level: number;
}
export interface ExtractHeadingsOptions {
/**
* A function to convert the heading title to a slug, if you wish to override the default slug generation algorithm
*
* @param title The heading to slugify
* @returns The slugified heading
*/
slugFn?: (title: string) => string;
}
/**
* @description gets all the heading-text from a markdown file
* @param {string} filePath a valid relative path, as a string to where the markdown file is located.
* @param {Object} options an optional configuration object to customize the behaviour of the function
* @returns an array of objects containing the heading information like the `id`, `title`, `slug`, and `level`
* @see [Documentation](https://github.com/kaf-lamed-beyt/extract-md-headings#usage)
*/
export function extractHeadings(
filePath: string,
options?: ExtractHeadingsOptions
): Array<Heading> {
const content = fs.readFileSync(filePath, "utf-8");
const headings: Array<Heading> = [];
// match the `#` syntax for headings
const headingMatcher = /^(#+)\s(.+)$/gm;
let match = headingMatcher.exec(content);
while (match !== null) {
const id = Math.floor(Math.random() * 900000) + 100000;
const level = match[1].length;
const title = match[2].trim();
const slugFn = options?.slugFn ?? defaultSlugFn;
const slug = slugFn(title);
headings.push({ id, slug, title, level });
match = headingMatcher.exec(content);
}
return headings;
}
const defaultSlugFn = (title: string): string => {
return title
.toLowerCase()
.replace(/[^\w\s-]/g, "")
.replace(/\s+/g, "-");
};