hast-util-to-string is a utility within the `unified` ecosystem designed to extract the plain-text value of a `hast` (HTML Abstract Syntax Tree) node. It strictly mimics the DOM's `Node#textContent` getter, returning all textual content regardless of styling or layout, and importantly, it does not interpret HTML elements like `<br>` as introducing newlines. This behavior differentiates it from `hast-util-to-text`, which emulates `Node#innerText` by considering rendered output. The current stable version is 3.0.1. As part of the actively maintained `unified` collective, it follows a release cadence tied to the broader ecosystem, with major versions often introducing updated Node.js requirements (e.g., Node.js 16+ for v3) and migrating to modern JavaScript module practices, including being ESM-only and utilizing package `exports` fields. The library provides comprehensive TypeScript type definitions, ensuring robust development.
npm install hast-util-to-stringVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to convert both simple and complex HAST nodes into their plain-text representations using `hast-util-to-string`, highlighting its `Node#textContent`-like behavior.
Migrate your project to use ES module syntax. For Node.js, ensure your `package.json` specifies `"type": "module"` or use `.mjs` file extensions. Update bundler configurations if applicable.
Upgrade your Node.js environment to version 16 or newer. Use `nvm` or other version managers for easier switching.
If line breaks or other layout-aware text extraction is needed, switch to `hast-util-to-text`. Otherwise, ensure your code accounts for `textContent` behavior.
Always use a sanitizer like `rehype-sanitize` on `hast` trees before serializing them back to HTML, especially when dealing with untrusted user input.
Change `const { toString } = require('hast-util-to-string')` to `import { toString } from 'hast-util-to-string'`. Ensure your project is configured for ES modules (e.g., `"type": "module"` in `package.json`).Ensure you are using a named import: `import { toString } from 'hast-util-to-string'` instead of `import toString from 'hast-util-to-string'`.No dependency data recorded yet.