Skip to content

Commit

Permalink
Fix Global RegExp -- consistency with non-global flag (since global w…
Browse files Browse the repository at this point in the history
…as sortof implicit) Fixes #72
  • Loading branch information
fbartho committed Jun 11, 2020
1 parent a9094c0 commit 875230c
Show file tree
Hide file tree
Showing 2 changed files with 111 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/lib/TextExtraction.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class TextExtraction {
textLeft = textLeft.substr(matches.index + matches[0].length);
indexOfMatchedString += matches[0].length - 1;
// Global RegExps are stateful, this makes it operate on the "remainder" of the string
pattern.pattern.lastIndex = indexOfMatchedString;
pattern.pattern.lastIndex = 0;
}

parts.push({ children: textLeft });
Expand Down
110 changes: 110 additions & 0 deletions test/TextExtraction.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,116 @@ describe('TextExtraction', () => {
`);
});

it('handles global flagged regexps consistently', () => {
const lol = 'lol lol lol lol lol lol lol lol';
// The way this library is constructed, matches progressively consume
const extractGlobal = new TextExtraction(lol, [
{ pattern: new RegExp('lol', 'gi') },
]);
expect(extractGlobal.parse()).toMatchInlineSnapshot(`
Array [
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
]
`);

const extractNonGlobal = new TextExtraction(lol, [
{ pattern: new RegExp('lol', 'i') },
]);
expect(extractNonGlobal.parse()).toMatchInlineSnapshot(`
Array [
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
Object {
"children": " ",
},
Object {
"children": "lol",
},
]
`);
});

it('respects the parsing order', () => {
const textExtraction = new TextExtraction(
'hello my website is http://foo.bar, bar is good.',
Expand Down

0 comments on commit 875230c

Please sign in to comment.