Bulletproof getCountOfAllMatches against non-global regex input

FREEBIE
This commit is contained in:
Scott Nonnenberg 2017-05-10 15:28:22 -07:00
parent 423a0fef67
commit 0496518af4
2 changed files with 16 additions and 0 deletions

View file

@ -21,6 +21,10 @@
var match = regex.exec(str);
var count = 0;
if (!regex.global) {
return match ? 1 : 0;
}
while (match) {
count += 1;
match = regex.exec(str);

View file

@ -20,6 +20,18 @@ describe('EmojiUtil', function() {
var actual = emoji.getCountOfAllMatches(str, r);
assert.equal(actual, 2);
});
it('returns zero for no match with non-global regular expression', function() {
var r = /s/g;
var str = 'no match';
var actual = emoji.getCountOfAllMatches(str, r);
assert.equal(actual, 0);
});
it('returns 1 for match with non-global regular expression', function() {
var r = /s/;
var str = 's + s';
var actual = emoji.getCountOfAllMatches(str, r);
assert.equal(actual, 1);
});
});
describe('hasNormalCharacters', function() {