The `hast-util-find-and-replace` package is a utility within the unifiedjs ecosystem designed to efficiently find and replace patterns (strings or regular expressions) within a HAST (HTML Abstract Syntax Tree). It operates by traversing the tree in a preorder fashion and applying replacements specifically within `Text` nodes. A key feature is its awareness of HTML structure, allowing it to ignore certain tags like `<script>`, `<style>`, `<iframe>`, `<img>`, and `<a>` by default, preventing unintended modifications. The current stable version is 5.0.1. The package maintains an active release cadence, with frequent patch and minor updates, and significant breaking changes between major versions. Its primary differentiator is its tight integration with HAST, offering a robust and context-aware solution for HTML tree manipulation.
npm install hast-util-find-and-replaceVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to import `findAndReplace` and use it to modify a HAST tree. It shows various replacement patterns, including strings, regular expressions, and functions that generate new HAST nodes, and how to pass options like `ignore`.
Ensure your project is configured for ESM (e.g., `type: "module"` in `package.json` or `.mjs` file extension) and running Node.js 16 or newer. Update `require()` statements to `import` statements.
Rewrite the `list` argument from an object structure (e.g., `{ 'foo': 'bar' }`) to an array of tuples (e.g., `[['foo', 'bar']]`) or a single tuple `['foo', 'bar']`.Retain a reference to the `tree` object passed to `findAndReplace` as it is modified in place; do not expect a return value.
Structure your HAST tree such that text to be replaced is contained entirely within individual `Text` nodes. For multi-node replacements, custom traversal and manipulation logic might be required.
If you need to replace text within these ignored tags, provide a custom `ignore` array in the options (e.g., `options: { ignore: [] }` to disable all ignores, or `options: { ignore: ['math', 'script'] }` for a partial override).Convert your consuming file or project to use ES modules by setting `"type": "module"` in `package.json` or by using `.mjs` file extensions, and update `require()` calls to `import` statements.
Ensure you are using a named import: `import { findAndReplace } from 'hast-util-find-and-replace'`.Refactor the `list` argument. Instead of `{ 'pattern': 'replacement' }`, use `[['pattern', 'replacement']]` or `['pattern', 'replacement']`.No dependency data recorded yet.