UNPKG

2.45 kBMarkdownView Raw
1# mdtocs
2
3[![NPM](https://nodei.co/npm/mdtocs.png)](https://nodei.co/npm/mdtocs/)
4
5[![NPM version](https://img.shields.io/npm/v/mdtocs.svg)](https://www.npmjs.com/package/mdtocs)
6[![Build Status](https://github.com/remarkablemark/mdtocs/workflows/build/badge.svg?branch=master)](https://github.com/remarkablemark/mdtocs/actions?query=workflow%3Abuild)
7[![codecov](https://codecov.io/gh/remarkablemark/mdtocs/branch/master/graph/badge.svg?token=IK2QDLEOVB)](https://codecov.io/gh/remarkablemark/mdtocs)
8
9[Markdown](https://wikipedia.org/wiki/Markdown) table of contents generator:
10
11```
12mdtocs(string)
13```
14
15This library uses [regex](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions) to parse [Markdown headings](https://www.markdownguide.org/basic-syntax/#headings). As a result, edge cases like headings with links and images won't be generated correctly. Inspired by the [blog post](https://b.remarkabl.org/3rgdgCk).
16
17#### Example
18
19```js
20const { mdtocs } = require('mdtocs');
21mdtocs('# Hello, World!'); // '- [Hello, World!](#hello-world)'
22```
23
24[Site](https://b.remarkabl.org/mdtocs) | [Replit](https://replit.com/@remarkablemark/mdtocs) | [JSFiddle](https://jsfiddle.net/remarkablemark/dr03pLxn/)
25
26## Install
27
28[NPM](https://www.npmjs.com/package/mdtocs):
29
30```sh
31npm install mdtocs --save
32```
33
34[Yarn](https://yarnpkg.com/package/mdtocs):
35
36```sh
37yarn add mdtocs
38```
39
40[CDN](https://unpkg.com/mdtocs/):
41
42```html
43<script src="https://unpkg.com/mdtocs@latest/umd/mdtocs.min.js"></script>
44<script>
45 window.mdtocs.mdtocs(/* string */);
46</script>
47```
48
49## Usage
50
51Import with ES Modules:
52
53```js
54import { mdtocs } from 'mdtocs';
55```
56
57Or require with CommonJS:
58
59```js
60const { mdtocs } = require('mdtocs');
61```
62
63Generate table of contents from Markdown:
64
65```js
66mdtocs(`
67# Heading 1
68## Heading 2
69### Heading 3
70`);
71```
72
73Output:
74
75```md
76- [Heading 1](#heading-1)
77 - [Heading 2](#heading-2)
78 - [Heading 3](#heading-3)
79```
80
81If the first argument is not a string, then an error will be thrown:
82
83```js
84mdtocs(); // TypeError: First argument must be a string
85```
86
87## Testing
88
89Run tests with coverage:
90
91```sh
92npm test
93```
94
95Run tests in watch mode:
96
97```sh
98npm run test:watch
99```
100
101Lint files:
102
103```sh
104npm run lint
105```
106
107Fix lint errors:
108
109```sh
110npm run lint:fix
111```
112
113## Release
114
115Release is automated with [Release Please](https://github.com/googleapis/release-please).
116
117## License
118
119[MIT](https://github.com/remarkablemark/mdtocs/blob/master/LICENSE)