Registry / serialization / hast-util-find-and-replace

hast-util-find-and-replace

JSON →
library5.0.1jsnpmunverified

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-replace
INSTALL
IMPORT
SIG · HAST-UTIL-FIND-AND
H
hast-util-find-and-replace
serializationjavascriptv5.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

findAndReplace
import { findAndReplace } from 'hast-util-find-and-replace'
const findAndReplace = require('hast-util-find-and-replace')
Package is ESM-only since v4 and requires Node.js 16+ for v5. Use `import` syntax.
defaultIgnore
import { defaultIgnore } from 'hast-util-find-and-replace'
import defaultIgnore from 'hast-util-find-and-replace'
This is a named export, not a default export.
FindAndReplaceList
import type { FindAndReplaceList } from 'hast-util-find-and-replace'
Import types separately for type-checking without runtime implications.

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`.

import { h } from 'hastscript'; import { findAndReplace } from 'hast-util-find-and-replace'; import { inspect } from 'unist-util-inspect'; // For visualizing the tree const tree = h('p', [ 'Some ', h('em', 'emphasis'), ', ', h('strong', 'importance'), ', and ', h('code', 'code'), '.' ]); // Apply find and replace operations findAndReplace( tree, [ [/and/gi, 'or'], // Replace 'and' with 'or' (case-insensitive) [/emphasis/gi, 'em'], // Replace 'emphasis' with 'em' [/importance/gi, 'strong'], // Replace 'importance' with 'strong' [ /code/gi, function ($0) { return h('a', {href: '//example.com#' + $0}, $0) // Replace 'code' with a link } ], ['Some', (match, node, index, parent) => { // Example of custom replacement logic, accessing node context console.log(`Found "${match}" at index ${index} in parent:`, parent.type); return 'Any'; // Replace "Some" with "Any" }] ], { ignore: ['code'] // Also ignore 'code' tags in addition to defaults like script/style } ); console.log(inspect(tree));
Debug
Known issues
breakingThe package transitioned to ESM-only and requires Node.js 16 or newer for version 5.x. Older Node.js versions or CommonJS environments are not supported.
fix
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.
affects: >=5.0.0
breakingThe API for `findAndReplace` changed to accept only a tuple `[Find, Replace]` or a list of tuples `[[Find, Replace], ...]`. Directly passing an object for `list` is no longer supported.
fix
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']`.
affects: >=5.0.0
breakingThe `findAndReplace` function now yields `undefined` (returns nothing). It mutates the provided `tree` node directly. If you need to keep a reference to the modified tree, you must pass the original tree object and expect it to be modified in place.
fix
Retain a reference to the `tree` object passed to `findAndReplace` as it is modified in place; do not expect a return value.
affects: >=5.0.0
gotchaThe utility only finds patterns within `Text` nodes and processes complete matches. It does not handle partial matches that span across multiple HAST nodes (e.g., a word broken by an HTML tag).
fix
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.
affects: >=1.0.0
gotchaBy default, `findAndReplace` ignores content within `<math>`, `<script>`, `<style>`, `<svg>`, and `<title>` elements to prevent unintended modifications to code or metadata. This default can be overridden.
fix
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).
affects: >=1.0.0
Errors
Common errors & fixes
ERR_REQUIRE_ESM
Attempting to import `hast-util-find-and-replace` using `require()` syntax in a CommonJS context, but the package is ESM-only.
fix
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.
TypeError: (0 , _hast_util_find_and_replace__WEBPACK_IMPORTED_MODULE_0__.findAndReplace) is not a function
This error typically indicates an incorrect import statement, where `findAndReplace` is being treated as a default import when it is a named export.
fix
Ensure you are using a named import: `import { findAndReplace } from 'hast-util-find-and-replace'`.
TypeError: The 'list' argument must be a tuple or a list of tuples
In `hast-util-find-and-replace` v5.x, the `list` argument for `findAndReplace` must be an array of `[find, replace]` tuples or a single `[find, replace]` tuple. Passing an object is deprecated and no longer supported.
fix
Refactor the `list` argument. Instead of `{ 'pattern': 'replacement' }`, use `[['pattern', 'replacement']]` or `['pattern', 'replacement']`.
Upgrade
Version history
5.0.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
8 hits · last 30 days
node
8
Resources