Skip to content

Commit 8c7e552

Browse files
committed
Add improved docs
1 parent 543af1b commit 8c7e552

File tree

3 files changed

+133
-73
lines changed

3 files changed

+133
-73
lines changed

index.js

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
/**
22
* @typedef {import('./lib/index.js').Options} Options
3-
* @typedef {import('./lib/index.js').RegExpMatchObject} RegExpMatchObject
43
* @typedef {import('./lib/index.js').Find} Find
54
* @typedef {import('./lib/index.js').Replace} Replace
65
* @typedef {import('./lib/index.js').ReplaceFunction} ReplaceFunction

lib/index.js

-4
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,6 @@
1212
* @typedef {import('hast-util-is-element').Test} Test
1313
* @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult
1414
*
15-
* @typedef RegExpMatchObject
16-
* @property {number} index
17-
* @property {string} input
18-
*
1915
* @typedef {string|RegExp} Find
2016
* @typedef {string|ReplaceFunction} Replace
2117
*

readme.md

+133-68
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,64 @@
88
[![Backers][backers-badge]][collective]
99
[![Chat][chat-badge]][chat]
1010

11-
[**hast**][hast] utility to find and replace text in a [*tree*][tree].
11+
[hast][] utility to find and replace things.
1212

13-
## Install
13+
## Contents
14+
15+
* [What is this?](#what-is-this)
16+
* [When should I use this?](#when-should-i-use-this)
17+
* [Install](#install)
18+
* [Use](#use)
19+
* [API](#api)
20+
* [`findAndReplace(tree, find, replace[, options])`](#findandreplacetree-find-replace-options)
21+
* [Types](#types)
22+
* [Compatibility](#compatibility)
23+
* [Security](#security)
24+
* [Related](#related)
25+
* [Contribute](#contribute)
26+
* [License](#license)
27+
28+
## What is this?
29+
30+
This package is a utility that lets you find patterns (`string`, `RegExp`) in
31+
text and replace them with nodes (such as elements).
32+
It’s aware of HTML (such as ignoring `<style>` and `<script>` by default).
1433

15-
This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c):
16-
Node 12+ is needed to use it and it must be `import`ed instead of `require`d.
34+
## When should I use this?
1735

18-
[npm][]:
36+
This utility is typically useful when you have regexes and want to modify hast.
37+
One example is when you have some form of “mentions” (such as
38+
`/@([a-z][_a-z0-9])\b/gi`) and want to create links to persons from them.
39+
40+
## Install
41+
42+
This package is [ESM only][esm].
43+
In Node.js (version 12.20+, 14.14+, or 16.0+), install with [npm][]:
1944

2045
```sh
2146
npm install hast-util-find-and-replace
2247
```
2348

49+
In Deno with [`esm.sh`][esmsh]:
50+
51+
```js
52+
import {findAndReplace} from 'https://esm.sh/hast-util-find-and-replace@4'
53+
```
54+
55+
In browsers with [`esm.sh`][esmsh]:
56+
57+
```html
58+
<script type="module">
59+
import {findAndReplace} from 'https://esm.sh/hast-util-find-and-replace@4?bundle'
60+
</script>
61+
```
62+
2463
## Use
2564

2665
```js
2766
import {h} from 'hastscript'
28-
import {inspect} from 'unist-util-inspect'
2967
import {findAndReplace} from 'hast-util-find-and-replace'
68+
import {inspect} from 'unist-util-inspect'
3069

3170
const tree = h('p', [
3271
'Some ',
@@ -38,48 +77,55 @@ const tree = h('p', [
3877
'.'
3978
])
4079

41-
findAndReplace(tree, 'and', 'or')
42-
43-
findAndReplace(tree, {emphasis: 'em', importance: 'strong'})
44-
45-
findAndReplace(tree, {
46-
code: function($0) {
47-
return h('a', {href: '//example.com#' + $0}, $0)
48-
}
49-
})
80+
findAndReplace(tree, [
81+
[/and/gi, 'or'],
82+
[/emphasis/gi, 'em'],
83+
[/importance/gi, 'strong'],
84+
[
85+
/code/gi,
86+
function ($0) {
87+
return h('a', {href: '//example.com#' + $0}, $0)
88+
}
89+
]
90+
])
5091

5192
console.log(inspect(tree))
5293
```
5394

5495
Yields:
5596

5697
```txt
57-
element[9] [tagName="p"]
58-
├─ text: "Some "
59-
├─ element[1] [tagName="em"]
60-
│ └─ text: "em"
61-
├─ text: ", "
62-
├─ element[1] [tagName="strong"]
63-
│ └─ text: "strong"
64-
├─ text: ", "
65-
├─ text: "or"
66-
├─ text: " "
67-
├─ element[1] [tagName="code"]
68-
│ └─ element[1] [tagName="a"][properties={"href":"//example.com#code"}]
69-
│ └─ text: "code"
70-
└─ text: "."
98+
element<p>[9]
99+
│ properties: {}
100+
├─0 text "Some "
101+
├─1 element<em>[1]
102+
│ │ properties: {}
103+
│ └─0 text "em"
104+
├─2 text ", "
105+
├─3 element<strong>[1]
106+
│ │ properties: {}
107+
│ └─0 text "strong"
108+
├─4 text ", "
109+
├─5 text "or"
110+
├─6 text " "
111+
├─7 element<code>[1]
112+
│ │ properties: {}
113+
│ └─0 element<a>[1]
114+
│ │ properties: {"href":"//example.com#code"}
115+
│ └─0 text "code"
116+
└─8 text "."
71117
```
72118

73119
## API
74120

75-
This package exports the following identifiers: `findAndReplace`, `defaultIgnore`.
121+
This package exports the identifiers `findAndReplace` and `defaultIgnore`.
76122
There is no default export.
77123

78-
### `findAndReplace(tree, find[, replace][, options])`
124+
### `findAndReplace(tree, find, replace[, options])`
79125

80-
Find and replace text in a [**hast**][hast] [*tree*][tree].
81-
The algorithm searches the tree in [*preorder*][preorder] for complete values
82-
in [`Text`][text] nodes.
126+
Find patterns in a tree and replace them.
127+
The algorithm searches the tree in *[preorder][]* for complete values in
128+
[`Text`][text] nodes.
83129
Partial matches are not supported.
84130

85131
###### Signatures
@@ -90,43 +136,56 @@ Partial matches are not supported.
90136
###### Parameters
91137

92138
* `tree` ([`Node`][node])
93-
[**hast**][hast] [*tree*][tree]
94139
* `find` (`string` or `RegExp`)
95-
Value to find and remove.
96-
When `string`, escaped and made into a global `RegExp`
140+
value to find and remove (`string`s are escaped and turned into a global
141+
`RegExp`)
97142
* `replace` (`string` or `Function`)
98-
— Value to insert.
99-
When `string`, turned into a [`Text`][text] node.
100-
When `Function`, called with the results of calling `RegExp.exec` as
101-
arguments, in which case it can return a [`Node`][node] or a `string` (which
102-
is wrapped in a [`Text`][text] node), or `false` to not replace
103-
* `search` (`Object` or `Array`)
104-
— Perform multiple find-and-replaces.
105-
When `Array`, each entry is a tuple (`Array`) of a `find` (at `0`) and
106-
`replace` (at `1`).
107-
When `Object`, each key is a `find` (in string form) and each value is a
108-
`replace`
143+
— value to insert.
144+
`string`s are turned into a [`Text`][text] node,
145+
`Function`s are called with the results of calling `RegExp.exec` as
146+
arguments, and they can return a [`Node`][node], a `string` (which is
147+
wrapped in a [`Text`][text] node), or `false` to not replace
148+
* `search` (`Array` or `Object`)
149+
— perform multiple find-and-replaces.
150+
Either an `Array` of tuples (`Array`s) with `find` (at `0`) and `replace`
151+
(at `1`), or an `Object` where each key is `find` and each value is
152+
the corresponding `replace`
109153
* `options.ignore` (`Test`, default: `['title', 'script', 'style', 'svg',
110154
'math']`)
111-
Any [`hast-util-is-element`][test] compatible test.
112-
The default list is exported as `defaultIgnore`
155+
any [`hast-util-is-element`][test] compatible test (the default list is
156+
exported as `defaultIgnore`)
113157

114158
###### Returns
115159

116-
The given, modified, `tree`.
160+
The given `tree` ([`Node`][node]).
161+
162+
## Types
163+
164+
This package is fully typed with [TypeScript][].
165+
It exports the additional types `Find`, `Replace`, `ReplaceFunction`,
166+
`FindAndReplaceTuple`, `FindAndReplaceSchema`, `FindAndReplaceList`, and
167+
`Options`.
168+
169+
## Compatibility
170+
171+
Projects maintained by the unified collective are compatible with all maintained
172+
versions of Node.js.
173+
As of now, that is Node.js 12.20+, 14.14+, and 16.0+.
174+
Our projects sometimes work with older versions, but this is not guaranteed.
117175

118176
## Security
119177

120-
Improper use of the `replace` can open you up to a
121-
[cross-site scripting (XSS)][xss] attack as the value of `replace` is injected
122-
into the syntax tree.
178+
Use of `hast-util-find-and-replace` can open you up to a
179+
[cross-site scripting (XSS)][xss] attack if a value used to `replace` is unsafe.
180+
Use [`hast-util-santize`][hast-util-sanitize] to make the hast tree safe.
181+
123182
The following example shows how a script is injected that runs when loaded in a
124183
browser.
125184

126185
```js
127-
findAndReplace(h('p', 'This and that.'), 'and', function() {
128-
return h('script', 'alert(1)')
129-
})
186+
const tree = h('p', 'This and that.')
187+
188+
findAndReplace(tree, 'and', () => h('script', 'alert(1)'))
130189
```
131190

132191
Yields:
@@ -135,23 +194,23 @@ Yields:
135194
<p>This <script>alert(1)</script> that.</p>
136195
```
137196

138-
Do not use user input in `replace` or use [`hast-util-santize`][sanitize].
139-
140197
## Related
141198

142199
* [`hast-util-select`](https://github.com/syntax-tree/hast-util-select)
143200
`querySelector`, `querySelectorAll`, and `matches`
201+
* [`mdast-util-find-and-replace`](https://github.com/syntax-tree/mdast-util-find-and-replace)
202+
— find and replace in mdast
144203
* [`unist-util-select`](https://github.com/syntax-tree/unist-util-select)
145204
— select unist nodes with CSS-like selectors
146205

147206
## Contribute
148207

149-
See [`contributing.md` in `syntax-tree/.github`][contributing] for ways to get
150-
started.
208+
See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for
209+
ways to get started.
151210
See [`support.md`][support] for ways to get help.
152211

153212
This project has a [code of conduct][coc].
154-
By interacting with this repository, organization, or community you agree to
213+
By interacting with this repository, organisation, or community you agree to
155214
abide by its terms.
156215

157216
## License
@@ -188,28 +247,34 @@ abide by its terms.
188247

189248
[npm]: https://docs.npmjs.com/cli/install
190249

250+
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
251+
252+
[esmsh]: https://esm.sh
253+
254+
[typescript]: https://www.typescriptlang.org
255+
191256
[license]: license
192257

193258
[author]: https://wooorm.com
194259

195-
[contributing]: https://github.com/syntax-tree/.github/blob/HEAD/contributing.md
260+
[health]: https://github.com/syntax-tree/.github
196261

197-
[support]: https://github.com/syntax-tree/.github/blob/HEAD/support.md
262+
[contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md
198263

199-
[coc]: https://github.com/syntax-tree/.github/blob/HEAD/code-of-conduct.md
264+
[support]: https://github.com/syntax-tree/.github/blob/main/support.md
265+
266+
[coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md
200267

201268
[hast]: https://github.com/syntax-tree/hast
202269

203270
[node]: https://github.com/syntax-tree/hast#ndoes
204271

205-
[tree]: https://github.com/syntax-tree/unist#tree
206-
207272
[preorder]: https://github.com/syntax-tree/unist#preorder
208273

209274
[text]: https://github.com/syntax-tree/hast#text
210275

211276
[xss]: https://en.wikipedia.org/wiki/Cross-site_scripting
212277

213-
[sanitize]: https://github.com/syntax-tree/hast-util-sanitize
278+
[hast-util-sanitize]: https://github.com/syntax-tree/hast-util-sanitize
214279

215280
[test]: https://github.com/syntax-tree/hast-util-is-element#api

0 commit comments

Comments
 (0)