unified

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

Package: hast-util-find-and-replace@4.0.0

  1. Dependencies: 0·Dependents: 1
  2. hast utility to find and replace text in a tree
  1. util 137
  2. utility 133
  3. unist 121
  4. html 112
  5. hast 61
  6. hast-util 40
  7. find 10
  8. replace 2

hast-util-find-and-replace

Build Coverage Downloads Size Sponsors Backers Chat

hast 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 hast-util-find-and-replace

Use

import {h} from 'hastscript'
import {inspect} from 'unist-util-inspect'
import {findAndReplace} from 'hast-util-find-and-replace'

var tree = h('p', [
  'Some ',
  h('em', 'emphasis'),
  ', ',
  h('strong', 'importance'),
  ', and ',
  h('code', 'code'),
  '.'
])

findAndReplace(tree, 'and', 'or')

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

findAndReplace(tree, {
  code: function($0) {
    return h('a', {href: '//example.com#' + $0}, $0)
  }
})

console.log(inspect(tree))

Yields:

element[9] [tagName="p"]
├─ text: "Some "
├─ element[1] [tagName="em"]
│  └─ text: "em"
├─ text: ", "
├─ element[1] [tagName="strong"]
│  └─ text: "strong"
├─ text: ", "
├─ text: "or"
├─ text: " "
├─ element[1] [tagName="code"]
│  └─ element[1] [tagName="a"][properties={"href":"//example.com#code"}]
│     └─ text: "code"
└─ text: "."

API

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

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

Find and replace text in a hast tree. 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

Improper use of the replace can open you up to a cross-site scripting (XSS) attack as the value of replace is injected into the syntax tree. The following example shows how a script is injected that runs when loaded in a browser.

findAndReplace(h('p', 'This and that.'), 'and', function() {
  return h('script', 'alert(1)')
})

Yields:

<p>This <script>alert(1)</script> that.</p>

Do not use user input in replace or use hast-util-santize.

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