hast-util-excerpt: HTML Tree Excerpt Utility

2.0.0 · active · verified Sun Apr 19

hast-util-excerpt is a utility within the unified (specifically hast/rehype) ecosystem designed to truncate an HTML (hast) syntax tree based on an explicit comment marker, typically `<!--more-->`. This allows authors to precisely define where a document's 'excerpt' or 'summary' should end, offering more control than character-count-based truncation methods. The current stable version is 2.0.0, which introduced significant breaking changes by moving to ESM-only and requiring Node.js 16 or newer. Releases occur as changes accumulate, rather than on a fixed schedule. Its primary differentiator is the author-defined explicit truncation point, making it suitable for content management systems or static site generators where content creators need fine-grained control over document summaries. It works by traversing the tree and stopping at the specified comment, returning a modified clone of the original tree.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates truncating a hast (HTML) tree at a `<!--more-->` comment marker, including an example with a custom comment.

import { u } from 'unist-builder';
import { h } from 'hastscript';
import { excerpt } from 'hast-util-excerpt';

const tree = h('p', [
  'Lorem ipsum dolor sit amet, ',
  h('em', 'consectetur'),
  'adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
  u('comment', 'more'),
  'Ut enim ad minim veniam, quis nostrud'
]);

const result = excerpt(tree);
console.log(JSON.stringify(result, null, 2));

const customCommentTree = h('div', [
  h('h1', 'My Article'),
  h('p', 'Introduction to the topic.'),
  u('comment', '<!-- break -->'),
  h('p', 'More detailed content.')
]);

const customExcerptResult = excerpt(customCommentTree, { comment: '<!-- break -->' });
console.log('\nExcerpt with custom comment:\n', JSON.stringify(customExcerptResult, null, 2));

view raw JSON →