diff --git a/README.md b/README.md index 8e3c5be0..f5503403 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Utilities for [Hexo]. - [spawn](#spawncommand-args-options) - [stripHTML](#striphtmlstr) - [wordWrap](#wordwrapstr-options) +- [tocObj](#tocobjstr-options) - [truncate](#truncatestr-options) - [unescapeHTML](#unescapehtmlstr) - [url_for](#url_forpath-option) @@ -409,6 +410,67 @@ wordWrap('Once upon a time', {width: 1}) // Once\nupon\na\ntime ``` +### tocObj(str, [options]) + +Generate a table of contents in JSON format based on the given html string. + +Option | Description | Default +--- | --- | --- +`min_depth` | The minimum level of TOC | 0 +`max_depth` | The maximum level of TOC | 6 + + +``` js +const html = [ + '

Title 1

', + '

Title 1.1

', + '

Title 1.1.1

', + '

Title 1.2

', + '

Title 1.3

', + '

Title 1.3.1

', + '

Title 2

', + '

Title 2.1

' +].join('\n'); + +tocObj(html); +/* +[ + { text: 'Title 1', id: 'title_1', level: 1 }, + { text: 'Title 1.1', id: 'title_1_1', level: 2 }, + { text: 'Title 1.1.1', id: 'title_1_1_1', level: 3 }, + { text: 'Title 1.2', id: 'title_1_2', level: 2 }, + { text: 'Title 1.3', id: 'title_1_3', level: 2 }, + { text: 'Title 1.3.1', id: 'title_1_3_1', level: 3 }, + { text: 'Title 2', id: 'title_2', level: 1 }, + { text: 'Title 2.1', id: 'title_2_1', level: 2 }, +] +*/ + +tocObj(html, { min_depth: 2 }); +/* +[ + { text: 'Title 1.1', id: 'title_1_1', level: 2 }, + { text: 'Title 1.1.1', id: 'title_1_1_1', level: 3 }, + { text: 'Title 1.2', id: 'title_1_2', level: 2 }, + { text: 'Title 1.3', id: 'title_1_3', level: 2 }, + { text: 'Title 1.3.1', id: 'title_1_3_1', level: 3 }, + { text: 'Title 2.1', id: 'title_2_1', level: 2 }, +] +*/ + +tocObj(html, { max_depth: 2 }); +/* +[ + { text: 'Title 1', id: 'title_1', level: 1 }, + { text: 'Title 1.1', id: 'title_1_1', level: 2 }, + { text: 'Title 1.2', id: 'title_1_2', level: 2 }, + { text: 'Title 1.3', id: 'title_1_3', level: 2 }, + { text: 'Title 2', id: 'title_2', level: 1 }, + { text: 'Title 2.1', id: 'title_2_1', level: 2 }, +] +*/ +``` + ### truncate(str, [options]) Truncates a given text after a given `length` if text is longer than `length`. The last characters will be replaced with the `omission` option for a total length not exceeding `length`.