From 0496518af4c7cbcafec8e8be8456082b614222f6 Mon Sep 17 00:00:00 2001 From: Scott Nonnenberg Date: Wed, 10 May 2017 15:28:22 -0700 Subject: [PATCH] Bulletproof getCountOfAllMatches against non-global regex input FREEBIE --- js/emoji_util.js | 4 ++++ test/emoji_util_test.js | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/js/emoji_util.js b/js/emoji_util.js index f4659732e..bc53f6b3e 100644 --- a/js/emoji_util.js +++ b/js/emoji_util.js @@ -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); diff --git a/test/emoji_util_test.js b/test/emoji_util_test.js index e306f4c00..05741de03 100644 --- a/test/emoji_util_test.js +++ b/test/emoji_util_test.js @@ -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() {