0
# Utility Functions
1
2
Helper functions for custom TOC rendering and text processing. These utilities are exposed as static methods on the main toc function for advanced customization.
3
4
## Capabilities
5
6
### Slugify Function
7
8
Generate URL-safe slugs from heading text with customizable processing.
9
10
```javascript { .api }
11
/**
12
* Generate URL-safe slug from heading text
13
* @param {string} str - Text to slugify
14
* @param {Object} options - Slugify options
15
* @returns {string} URL-safe slug
16
*/
17
function slugify(str, options);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const toc = require('markdown-toc');
24
25
// Basic slugification
26
console.log(toc.slugify('Hello World'));
27
// Output: "hello-world"
28
29
// Handle special characters
30
console.log(toc.slugify('API & SDK Guide'));
31
// Output: "api--sdk-guide"
32
33
// Handle HTML tags (stripped by default)
34
console.log(toc.slugify('<code>Installation</code>'));
35
// Output: "installation"
36
37
// Custom slugify function
38
const result = toc('# Some Article', {
39
slugify: function(str) {
40
return '!' + str.replace(/[^\w]/g, '-') + '!';
41
}
42
});
43
// Slug becomes: "!Some-Article!"
44
```
45
46
### Linkify Function
47
48
Convert heading tokens into markdown links.
49
50
```javascript { .api }
51
/**
52
* Convert heading into markdown link
53
* @param {Object} token - Heading token object
54
* @param {Object} options - Linking options
55
* @returns {Object} Token with linkified content
56
*/
57
function linkify(token, options);
58
```
59
60
**Usage Examples:**
61
62
```javascript
63
const toc = require('markdown-toc');
64
65
// Process individual heading token
66
const token = {
67
content: 'Getting Started',
68
slug: 'getting-started',
69
lvl: 2
70
};
71
72
const linkedToken = toc.linkify(token);
73
console.log(linkedToken.content);
74
// Output: "[Getting Started](#getting-started)"
75
76
// Custom linkify function
77
const result = toc(markdown, {
78
linkify: function(token, text, slug, opts) {
79
return `• [${text}](${slug})`;
80
}
81
});
82
```
83
84
### Bullets Function
85
86
Render markdown list bullets from array of heading tokens.
87
88
```javascript { .api }
89
/**
90
* Render bullet list from heading tokens
91
* @param {Array} tokens - Array of heading tokens
92
* @param {Object} options - Bullet formatting options
93
* @returns {string} Formatted bullet list markdown
94
*/
95
function bullets(tokens, options);
96
```
97
98
**Usage Examples:**
99
100
```javascript
101
const toc = require('markdown-toc');
102
103
// Generate TOC and use custom bullet rendering
104
const result = toc(markdown);
105
const customBullets = toc.bullets(result.json, {
106
bullets: ['-', '+', '*'],
107
indent: ' '
108
});
109
110
console.log(customBullets);
111
// Uses different bullets for different levels
112
113
// Numeric bullets
114
const numericBullets = result.json
115
.map((token, index) => {
116
const indent = ' '.repeat(token.lvl - result.highest);
117
return `${indent}${index + 1}. ${token.content}`;
118
})
119
.join('\n');
120
```
121
122
### Titleize Function
123
124
Process and clean heading text for display.
125
126
```javascript { .api }
127
/**
128
* Process and clean heading text for display
129
* @param {string} str - Heading text to process
130
* @param {Object} options - Processing options
131
* @returns {string} Cleaned heading text
132
*/
133
function titleize(str, options);
134
```
135
136
**Usage Examples:**
137
138
```javascript
139
const toc = require('markdown-toc');
140
141
// Basic titleize (removes HTML tags, cleans whitespace)
142
console.log(toc.titleize('<span>Hello World</span>'));
143
// Output: "Hello World"
144
145
// Custom titleize function
146
const result = toc(markdown, {
147
titleize: function(str) {
148
return str.toUpperCase();
149
}
150
});
151
152
// Disable titleize
153
const result2 = toc(markdown, {
154
titleize: false
155
});
156
```
157
158
### Strip Function
159
160
Strip specified words or characters from heading text.
161
162
```javascript { .api }
163
/**
164
* Strip specified words or characters from heading text
165
* @param {string} str - Text to process
166
* @param {Object} options - Strip configuration
167
* @returns {string} Processed text
168
*/
169
function strip(str, options);
170
```
171
172
**Usage Examples:**
173
174
```javascript
175
const toc = require('markdown-toc');
176
177
// Strip with array of words
178
const result = toc(markdown, {
179
strip: ['API', 'Guide', 'Documentation']
180
});
181
182
// Strip with custom function
183
const result2 = toc(markdown, {
184
strip: function(str) {
185
return str.replace(/\[.*?\]/g, ''); // Remove bracketed text
186
}
187
});
188
189
// Direct usage of strip utility
190
console.log(toc.strip('API Documentation Guide', {
191
strip: ['API', 'Guide']
192
}));
193
// Output: "Documentation"
194
```
195
196
### Custom TOC Rendering
197
198
Combine utility functions for completely custom TOC rendering.
199
200
```javascript
201
const toc = require('markdown-toc');
202
203
function customTOC(markdown) {
204
// Generate base TOC data
205
const result = toc(markdown);
206
207
// Custom processing using utilities
208
const customEntries = result.json.map(heading => {
209
// Custom slug generation
210
const customSlug = toc.slugify(heading.content, {
211
slugify: str => str.toLowerCase().replace(/\s+/g, '_')
212
});
213
214
// Custom title processing
215
const customTitle = toc.titleize(heading.content, {
216
titleize: str => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
217
});
218
219
// Custom link format
220
const indent = ' '.repeat(heading.lvl - result.highest);
221
return `${indent}- [${customTitle}](#${customSlug})`;
222
});
223
224
return customEntries.join('\n');
225
}
226
227
// Usage
228
const customResult = customTOC(`
229
# API REFERENCE
230
## USER management
231
### create USER
232
`);
233
234
console.log(customResult);
235
// Output:
236
// - [Api reference](#api_reference)
237
// - [User management](#user_management)
238
// - [Create user](#create_user)
239
```
240
241
### Advanced Slug Customization
242
243
Handle complex slug generation scenarios.
244
245
```javascript
246
const toc = require('markdown-toc');
247
248
// Handle duplicate headings with custom numbering
249
function customSlugify(str, options) {
250
let baseSlug = str.toLowerCase()
251
.replace(/[^\w\s-]/g, '')
252
.replace(/\s+/g, '-');
253
254
if (options.num > 0) {
255
baseSlug += `-v${options.num}`;
256
}
257
258
return baseSlug;
259
}
260
261
const result = toc(markdown, {
262
slugify: customSlugify
263
});
264
265
// Handles international characters
266
const intlSlugify = (str) => {
267
return str.normalize('NFD')
268
.replace(/[\u0300-\u036f]/g, '') // Remove diacritics
269
.toLowerCase()
270
.replace(/[^\w\s-]/g, '')
271
.replace(/\s+/g, '-');
272
};
273
```