Skip to content

Commit 58ea07c

Browse files
arttantfu
andcommitted
fix(transformers): fix matching indices for word-highlight (#909)
* fix(transformerMetaWordHighlight): use regex instead of substring to find matching indices; add tests * chore: fix * chore: update --------- Co-authored-by: Anthony Fu <[email protected]>
1 parent 9221ea3 commit 58ea07c

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

packages/transformers/src/transformers/meta-highlight-word.ts

+12-6
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,17 @@ export function transformerMetaWordHighlight(
5555
}
5656
}
5757

58-
function findAllSubstringIndexes(str: string, substr: string): number[] {
59-
const indexes = []
60-
let i = -1
61-
// eslint-disable-next-line no-cond-assign
62-
while ((i = str.indexOf(substr, i + 1)) !== -1)
63-
indexes.push(i)
58+
export function findAllSubstringIndexes(str: string, substr: string): number[] {
59+
const indexes: number[] = []
60+
let cursor = 0
61+
while (true) {
62+
const index = str.indexOf(substr, cursor)
63+
if (index === -1 || index >= str.length)
64+
break
65+
if (index < cursor)
66+
break
67+
indexes.push(index)
68+
cursor = index + substr.length
69+
}
6470
return indexes
6571
}
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { expect, it } from 'vitest'
2-
import { parseMetaHighlightWords } from '../src/transformers/meta-highlight-word'
2+
import { findAllSubstringIndexes, parseMetaHighlightWords } from '../src/transformers/meta-highlight-word'
33

44
it('parseHighlightWords', () => {
55
expect(parseMetaHighlightWords('')).toEqual([])
66
expect(parseMetaHighlightWords('/hello/')).toEqual(['hello'])
77
expect(parseMetaHighlightWords('/ /f /hello/')).toEqual([' ', 'hello'])
88
expect(parseMetaHighlightWords('/foo bar/ /foo.bar\\/foo/')).toEqual(['foo bar', 'foo.bar/foo'])
9+
expect(findAllSubstringIndexes('xxx', 'xx')).toEqual([0])
10+
expect(findAllSubstringIndexes('xxxx', 'xx')).toEqual([0, 2])
911
})

0 commit comments

Comments
 (0)