hast utility to find and replace text in a tree.
npm:
npm install hast-util-find-and-replace
var h = require('hastscript')
var inspect = require('unist-util-inspect')
var findAndReplace = require('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: "."
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.
findAndReplace(tree, find, replace[, options])
findAndReplace(tree, search[, options])
tree
(Node
) — hast treefind
(string
orRegExp
) — Value to find and remove. Whenstring
, escaped and made into a globalRegExp
replace
(string
orFunction
) — Value to insert. Whenstring
, turned into aText
node. WhenFunction
, invoked with the results of callingRegExp.exec
as arguments, in which case it can return aNode
or astring
, which is in the latter case wrapped in aText
nodesearch
(Object
orArray
) — Perform multiple find-and-replace’s. WhenArray
, each entry is a tuple (Array
) of afind
(at0
) andreplace
(at1
). WhenObject
, each key is afind
(in string form) and each value is areplace
options.ignore
(Array
, default:['title', 'script', 'style', 'svg', 'math']
) — Tag-names of elements not to search. This list can be accessed atfindAndReplace.ignore
The given, modified, tree
.
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, organisation, or community you agree to abide by its terms.