mdast Find and Replace Utility

3.0.2 · active · verified Sun Apr 19

mdast-util-find-and-replace is a utility within the unifiedjs ecosystem designed to find patterns (strings or regular expressions) within the text nodes of an mdast (Markdown Abstract Syntax Tree) and replace them with new mdast nodes. The current stable version is 3.0.2. It typically receives updates for bug fixes and minor enhancements, with major versions introducing breaking changes less frequently, as seen with the transition to v3.0.0. Key differentiators include its tight integration with the mdast specification, its ability to produce complex node structures as replacements, and its focus on efficient, preorder traversal. It's particularly useful for transforming markdown content programmatically, such as converting specific text patterns into links, mentions, or other AST elements.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to import `findAndReplace`, construct an mdast tree using `unist-builder`, and then apply multiple find-and-replace operations, including string, regex, and function-based replacements, before inspecting the modified tree.

import {findAndReplace} from 'mdast-util-find-and-replace';
import {u} from 'unist-builder';
import {inspect} from 'unist-util-inspect';

const tree = u('paragraph', [
  u('text', 'Some '),
  u('emphasis', [u('text', 'emphasis')]),
  u('text', ' and '),
  u('strong', [u('text', 'importance')]),
  u('text', '.')
]);

findAndReplace(tree, [
  [/and/gi, 'or'],
  [/emphasis/gi, 'em'],
  [/importance/gi, 'strong'],
  [
    /Some/g,
    function ($0) {
      return u('link', {url: '//example.com#' + $0}, [u('text', $0)]);
    }
  ]
]);

console.log(inspect(tree));

view raw JSON →