unified

Project: syntax-tree/mdast-util-find-and-replace

Package: mdast-util-find-and-replace@2.1.0

  1. Dependents: 9
  2. mdast utility to find and replace text in a tree
  1. util 144
  2. utility 140
  3. markdown 139
  4. unist 127
  5. mdast 83
  6. mdast-util 31
  7. find 11
  8. replace 2

mdast-util-find-and-replace

Build Coverage Downloads Size Sponsors Backers Chat

mdast utility to find and replace text in a tree.

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install mdast-util-find-and-replace

Use

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

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', 'or')

findAndReplace(tree, {emphasis: 'em', importance: 'strong'})

findAndReplace(tree, {
  Some: function ($0) {
    return u('link', {url: '//example.com#' + $0}, [u('text', $0)])
  }
})

console.log(inspect(tree))

Yields:

paragraph[8]
├─ link[1] [url="//example.com#Some"]
│  └─ text: "Some"
├─ text: " "
├─ emphasis[1]
│  └─ text: "em"
├─ text: " "
├─ text: "or"
├─ text: " "
├─ strong[1]
│  └─ text: "strong"
└─ text: "."

API

This package exports the following identifiers: findAndReplace. There is no default export.

findAndReplace(tree, find[, replace][, options])

Find and replace text in mdast trees. The algorithm searches the tree in preorder for complete values in Text nodes. Partial matches are not supported.

Signatures
Parameters
Returns

The given, modified, tree.

Security

Use of mdast-util-find-and-replace does not involve hast or user content so there are no openings for cross-site scripting (XSS) attacks.

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer