hast-util-find-and-replace

5.0.1 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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));

view raw JSON →