Skip to content

Commit 11b9573

Browse files
committed
Fix to reset lastIndex at false result
1 parent d54a54e commit 11b9573

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Diff for: lib/index.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,12 @@ export function findAndReplace(tree, list, options) {
171171
}
172172

173173
// It wasn’t a match after all.
174-
if (value !== false) {
174+
if (value === false) {
175+
// False acts as if there was no match.
176+
// So we need to reset `lastIndex`, which currently being at the end of
177+
// the current match, to the beginning.
178+
find.lastIndex = position + 1
179+
} else {
175180
if (start !== position) {
176181
nodes.push({type: 'text', value: node.value.slice(start, position)})
177182
}

Diff for: test.js

+33
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
/**
2+
* @typedef {import('hast').Root} Root
3+
*/
4+
15
import assert from 'node:assert/strict'
26
import test from 'node:test'
37
import {h} from 'hastscript'
@@ -290,6 +294,35 @@ test('findAndReplace', async function (t) {
290294
assert.deepEqual(tree, create())
291295
})
292296

297+
await t.test('should not treat `false` as a match', async function () {
298+
/** @type {Root} */
299+
const tree = {type: 'root', children: [{type: 'text', value: ':1:2:'}]}
300+
301+
findAndReplace(tree, [
302+
/:(\d+):/g,
303+
/**
304+
* @param {string} _
305+
* @param {string} $1
306+
*/
307+
function (_, $1) {
308+
return $1 === '2' ? h('strong', $1) : false
309+
}
310+
])
311+
312+
assert.deepEqual(tree, {
313+
type: 'root',
314+
children: [
315+
{type: 'text', value: ':1'},
316+
{
317+
type: 'element',
318+
tagName: 'strong',
319+
properties: {},
320+
children: [{type: 'text', value: '2'}]
321+
}
322+
]
323+
})
324+
})
325+
293326
await t.test('should not be order-sensitive with strings', async function () {
294327
const tree = h('p', 'Some emphasis, importance, and code.')
295328

0 commit comments

Comments
 (0)