forked from K-Sato1995/react-toc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
45 lines (39 loc) · 1.3 KB
/
utils.ts
File metadata and controls
45 lines (39 loc) · 1.3 KB
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
// Removes # and connects each word with '-'.
// It also replaces !/? with '-'.
const createLink = (string: string): string => {
const shapedString = string
.toLowerCase()
.replace(/^#+\s/, "")
.trimRight();
const anchor = shapedString
.split(" ")
.join("-")
.replace(/[?!]/g, "-");
return anchor;
};
// It removes # from the given string. And it shortens the string if its longer than "stringLimit".
const createTitle = (string: string, stringLimit: number) => {
const rawTitle = string.replace(/^#+\s/g, "");
if (rawTitle.length >= stringLimit)
return `${rawTitle.slice(0, stringLimit)}..`;
return rawTitle;
};
// It extracts headings from the given markdownText.
const extractHeadingsFromMd = (
markdownText: string,
highestTargetHeadings: number,
lowestTargetHeadings: number
): RegExpMatchArray | null => {
const headingRegex = new RegExp(
`^#{${highestTargetHeadings},${lowestTargetHeadings}}\\s.+(\\n|\\r|\\r\\n)`,
"gm"
);
return markdownText.match(headingRegex);
};
const removeCodeBlockFromMd = (
markdownText: string
): string => {
const codeBlockRegex = new RegExp('((````.+?````)|(```.+?```)|(~~~.+?~~~))\n', 'gms');
return markdownText.replace(codeBlockRegex, '');
};
export { createLink, createTitle, extractHeadingsFromMd, removeCodeBlockFromMd };