hast-util-from-string

3.0.1 · active · verified Sun Apr 19

hast-util-from-string is a utility package within the unified and rehype ecosystem designed to efficiently set the plain-text value of a HAST (Hypertext Abstract Syntax Tree) node. It mimics the behavior of the DOM's `Node#textContent` setter, effectively replacing all children of a node with a single text node containing the provided string value. The current stable version is 3.0.1. As part of the unified collective, it follows a coordinated release cadence, often aligning major version bumps across related packages, though individual utilities receive minor and patch updates as needed. A key differentiator is its `textContent`-like behavior, contrasting with `hast-util-from-text` which emulates `innerText` and considers rendering specifics like line breaks and table cell separation. The library is ESM-only and fully typed with TypeScript.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize an empty HAST node and how to overwrite an existing node's children with a new plain-text string using `fromString`.

import { h } from 'hastscript';
import { fromString } from 'hast-util-from-string';

// Create an empty paragraph node
const p = h('p');

// Set its plain-text value
fromString(p, 'Alpha');
console.log('Paragraph with new text:', JSON.stringify(p, null, 2));
// Expected output: { type: 'element', tagName: 'p', properties: {}, children: [ { type: 'text', value: 'Alpha' } ] }

// Create a div with existing children
const div = h('div', [h('b', 'Bold'), ' and ', h('i', 'italic'), '.']);
console.log('Original div:', JSON.stringify(div, null, 2));

// Overwrite its content with new plain text
fromString(div, 'Charlie');
console.log('Div with overwritten text:', JSON.stringify(div, null, 2));
// Expected output: { type: 'element', tagName: 'div', properties: {}, children: [ { type: 'text', value: 'Charlie' } ] }

view raw JSON →