unist-util-findalldeprecated

Unist node finding utility. Useful for working with remark, rehype or retext.

Usage no npm install needed!

<script type="module">
  import unistUtilFindall from 'https://cdn.skypack.dev/unist-util-findall';
</script>

README

unist-util-findall

Unist utility to select everything in a tree that matches a given condition.
Useful for working with remark, rehype and retext.

Why?

unist-util-find returns as soon as a single match is found.
unist-util-find-all-after, unist-util-find-all-before, and unist-util-find-all-between, only search immediate children.*
unist-util-filter creates a new copy of each matched node.
findAll is a lot like unist-util-select, except that you can use object and function conditions.

*The findall phrase (no hyphen) was chosen to distinguish it from the find-all-xxx utilities).

Installation

npm install --save unist-util-findall

Usage

Example

var remark = require('remark')
var findAll = require('unist-util-findall')

remark()
  .use(function () {
    return function (tree) {
      // string condition
      console.log(findAll(tree, 'value'))

      // object condition
      console.log(findAll(tree, { value: 'emphasis' }))

      // function condition
      console.log(findAll(tree, function (node) {
        return node.type === 'inlineCode'
      }))
    }
  })
  .processSync('Some _emphasis_, **strongness**, and `code`.')

Result:

// string condition: 'value'
[
  { "type": "text", "value": "Some " },
  {  "type": "text",  "value": "emphasis" },
  {  "type": "text", "value": ", " },
  { "type": "text", "value": "strongness" },
  { "type": "text", "value": ", and " },
  { "type": "inlineCode", "value": "code" },
  { "type": "text", "value": "." }
]

// object condition: { value: 'emphasis' }
[
  { "type": "text", "value": "emphasis" }
]

// function condition: function (node) { return node.type === 'inlineCode' }
[
  { "type": "inlineCode", "value": "code" }
]

API

findAll(node, condition)

Returns an Array of zero or more nodes that match condition.

  • node (Node) - Node to search
  • condition (string, object or function) - Condition used to test each node. Behaviour depends on the type of the condition:
    • string finds first node with a truthy property matching string
    • object finds first node that has matching values for all properties of object
    • function finds first node for which function returns true when passed node as argument

License

MIT