{"id":10995,"library":"hast-util-find-and-replace","title":"hast-util-find-and-replace","description":"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.","status":"active","version":"5.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/syntax-tree/hast-util-find-and-replace","tags":["javascript","unist","hast","hast-util","util","utility","html","find","replace","typescript"],"install":[{"cmd":"npm install hast-util-find-and-replace","lang":"bash","label":"npm"},{"cmd":"yarn add hast-util-find-and-replace","lang":"bash","label":"yarn"},{"cmd":"pnpm add hast-util-find-and-replace","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Package is ESM-only since v4 and requires Node.js 16+ for v5. Use `import` syntax.","wrong":"const findAndReplace = require('hast-util-find-and-replace')","symbol":"findAndReplace","correct":"import { findAndReplace } from 'hast-util-find-and-replace'"},{"note":"This is a named export, not a default export.","wrong":"import defaultIgnore from 'hast-util-find-and-replace'","symbol":"defaultIgnore","correct":"import { defaultIgnore } from 'hast-util-find-and-replace'"},{"note":"Import types separately for type-checking without runtime implications.","symbol":"FindAndReplaceList","correct":"import type { FindAndReplaceList } from 'hast-util-find-and-replace'"}],"quickstart":{"code":"import { h } from 'hastscript';\nimport { findAndReplace } from 'hast-util-find-and-replace';\nimport { inspect } from 'unist-util-inspect'; // For visualizing the tree\n\nconst tree = h('p', [\n  'Some ',\n  h('em', 'emphasis'),\n  ', ',\n  h('strong', 'importance'),\n  ', and ',\n  h('code', 'code'),\n  '.'\n]);\n\n// Apply find and replace operations\nfindAndReplace(\n  tree,\n  [\n    [/and/gi, 'or'], // Replace 'and' with 'or' (case-insensitive)\n    [/emphasis/gi, 'em'], // Replace 'emphasis' with 'em'\n    [/importance/gi, 'strong'], // Replace 'importance' with 'strong'\n    [\n      /code/gi,\n      function ($0) {\n        return h('a', {href: '//example.com#' + $0}, $0) // Replace 'code' with a link\n      }\n    ],\n    ['Some', (match, node, index, parent) => {\n      // Example of custom replacement logic, accessing node context\n      console.log(`Found \"${match}\" at index ${index} in parent:`, parent.type);\n      return 'Any'; // Replace \"Some\" with \"Any\"\n    }]\n  ],\n  {\n    ignore: ['code'] // Also ignore 'code' tags in addition to defaults like script/style\n  }\n);\n\nconsole.log(inspect(tree));\n","lang":"typescript","description":"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`."},"warnings":[{"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.","message":"The 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.","severity":"breaking","affected_versions":">=5.0.0"},{"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']`.","message":"The 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.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Retain a reference to the `tree` object passed to `findAndReplace` as it is modified in place; do not expect a return value.","message":"The `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.","severity":"breaking","affected_versions":">=5.0.0"},{"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.","message":"The 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).","severity":"gotcha","affected_versions":">=1.0.0"},{"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).","message":"By 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","cause":"Attempting to import `hast-util-find-and-replace` using `require()` syntax in a CommonJS context, but the package is ESM-only.","error":"ERR_REQUIRE_ESM"},{"fix":"Ensure you are using a named import: `import { findAndReplace } from 'hast-util-find-and-replace'`.","cause":"This error typically indicates an incorrect import statement, where `findAndReplace` is being treated as a default import when it is a named export.","error":"TypeError: (0 , _hast_util_find_and_replace__WEBPACK_IMPORTED_MODULE_0__.findAndReplace) is not a function"},{"fix":"Refactor the `list` argument. Instead of `{ 'pattern': 'replacement' }`, use `[['pattern', 'replacement']]` or `['pattern', 'replacement']`.","cause":"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.","error":"TypeError: The 'list' argument must be a tuple or a list of tuples"}],"ecosystem":"npm"}