Skip to content

Commit e8f140e

Browse files
committed
Fix random matches are missed + add test
Alternative implementation to #47
1 parent 979f888 commit e8f140e

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/lib/TextExtraction.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ class TextExtraction {
5252
);
5353

5454
textLeft = textLeft.substr(matches.index + matches[0].length);
55-
indexOfMatchedString += matches[0].length;
55+
indexOfMatchedString += matches[0].length - 1;
5656
// Global RegExps are stateful, this makes it operate on the "remainder" of the string
5757
pattern.pattern.lastIndex = indexOfMatchedString;
5858
}

test/TextExtraction.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,34 @@ describe('TextExtraction', () => {
2828
expect(textExtraction.parse()).toEqual([{ children: 'abcdef' }]);
2929
});
3030

31+
it('still works even if the RegExp has a previously-used pattern', () => {
32+
const r = /c/g;
33+
r.lastIndex = 2;
34+
const textExtraction = new TextExtraction('cc something c something', [
35+
{ pattern: r, renderText: () => 'Found!' },
36+
]);
37+
38+
expect(textExtraction.parse()).toMatchInlineSnapshot(`
39+
Array [
40+
Object {
41+
"children": "Found!",
42+
},
43+
Object {
44+
"children": "Found!",
45+
},
46+
Object {
47+
"children": " something ",
48+
},
49+
Object {
50+
"children": "Found!",
51+
},
52+
Object {
53+
"children": " something",
54+
},
55+
]
56+
`);
57+
});
58+
3159
it('returns an array with text parts if there is matches', () => {
3260
const textExtraction = new TextExtraction(
3361
'hello my website is http://foo.bar, bar is good.',

0 commit comments

Comments
 (0)