Skip to content

Commit e0ffb6b

Browse files
committed
Fix bug when replacing and then not
Backports: syntax-tree/mdast-util-find-and-replace@b40a41f.
1 parent 9914895 commit e0ffb6b

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

lib/index.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ export function findAndReplace(tree, find, replace, options) {
117117
const replace = pairs[pairIndex][1]
118118
let start = 0
119119
const index = parent.children.indexOf(node)
120+
let change = false
120121
/** @type {Array<Content>} */
121122
let nodes = []
122123
/** @type {number|undefined} */
@@ -142,9 +143,7 @@ export function findAndReplace(tree, find, replace, options) {
142143
}
143144

144145
// It wasn’t a match after all.
145-
if (value === false) {
146-
position = undefined
147-
} else {
146+
if (value !== false) {
148147
if (start !== position) {
149148
nodes.push({type: 'text', value: node.value.slice(start, position)})
150149
}
@@ -156,6 +155,7 @@ export function findAndReplace(tree, find, replace, options) {
156155
}
157156

158157
start = position + match[0].length
158+
change = true
159159
}
160160

161161
if (!find.global) {
@@ -165,14 +165,14 @@ export function findAndReplace(tree, find, replace, options) {
165165
match = find.exec(node.value)
166166
}
167167

168-
if (position === undefined) {
169-
nodes = [node]
170-
} else {
168+
if (change) {
171169
if (start < node.value.length) {
172170
nodes.push({type: 'text', value: node.value.slice(start)})
173171
}
174172

175173
parent.children.splice(index, 1, ...nodes)
174+
} else {
175+
nodes = [node]
176176
}
177177

178178
return index + nodes.length

test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,18 @@ test('findAndReplace', (t) => {
215215
'should not be order-sensitive with strings'
216216
)
217217

218+
t.deepEqual(
219+
findAndReplace(h('p', 'aaa bbb'), [
220+
[
221+
/\b\w+\b/g,
222+
function (/** @type {string} */ value) {
223+
return value === 'aaa' ? h('strong', value) : false
224+
}
225+
]
226+
]),
227+
h('p', [h('strong', 'aaa'), ' bbb']),
228+
'should support a match, and then a `false`'
229+
)
218230
t.deepEqual(
219231
findAndReplace(h('p', 'Some emphasis, importance, and code.'), [
220232
[

0 commit comments

Comments
 (0)