Skip to content

Commit 6dba078

Browse files
committed
Fix to reset lastIndex at false result
1 parent 4e23a5e commit 6dba078

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

lib/index.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,12 @@ export function findAndReplace(tree, list, options) {
160160
}
161161

162162
// It wasn’t a match after all.
163-
if (value !== false) {
163+
if (value === false) {
164+
// False acts as if there was no match.
165+
// So we need to reset `lastIndex`, which currently being at the end of
166+
// the current match, to the beginning.
167+
find.lastIndex = position + 1
168+
} else {
164169
if (start !== position) {
165170
nodes.push({
166171
type: 'text',

test.js

+28
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
/**
2+
* @typedef {import('mdast').Root} Root
3+
*/
4+
15
import assert from 'node:assert/strict'
26
import test from 'node:test'
37
import {findAndReplace} from 'mdast-util-find-and-replace'
@@ -374,6 +378,30 @@ test('findAndReplace', async function (t) {
374378
)
375379
})
376380

381+
await t.test('should not treat `false` as a match', async function () {
382+
/** @type {Root} */
383+
const tree = {type: 'root', children: [{type: 'text', value: ':1:2:'}]}
384+
385+
findAndReplace(tree, [
386+
/:(\d+):/g,
387+
/**
388+
* @param {string} _
389+
* @param {string} $1
390+
*/
391+
function (_, $1) {
392+
return $1 === '2' ? u('strong', [u('text', $1)]) : false
393+
}
394+
])
395+
396+
assert.deepEqual(tree, {
397+
type: 'root',
398+
children: [
399+
{type: 'text', value: ':1'},
400+
{type: 'strong', children: [{type: 'text', value: '2'}]}
401+
]
402+
})
403+
})
404+
377405
await t.test('should not recurse into a replaced value', async function () {
378406
const tree = u('paragraph', [u('text', 'asd.')])
379407

0 commit comments

Comments
 (0)