0

function countSmileys(arr) {
    let regex = /^([:;])([-~])*([)D])$/
    if(arr.length === 0) {
        return 0;
    }
    return arr.filter(el => {
        return regex.test(el);
    })
}

console.log(countSmileys([':(', ';)', ':)', ';o>', ':(', ':>', ';~D']));

I wrote the code that verify to see if that is smiley face or not. for eyes, it takes only ':/;' , for nose, '-/~' (it is fine if there is a nose) for lips, ')/D'.

So, I wrote the regular expression with global flag first. then it only gives

[';)', ';~D']

I finally got the right result when I eliminated g flag.

[';)', ':)', ';~D']

I have been confused to use g flags. can anyone explain this?

GrafiCode
  • 3,307
  • 3
  • 26
  • 31
SH Kim
  • 99
  • 6
  • 1
    running a regex with the global flag on a string advances the regex's `lastIndex`. Reusing the regex will then not start at the first letter, but actually at the index after the match in the last string. – ASDFGerte Dec 12 '19 at 17:17
  • 1
    In the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#Using_test_on_a_regex_with_the_global_flag – epascarello Dec 12 '19 at 17:17
  • @ASDFGerte terrific comment. Could you please link some documentation, so that I for one can add it to my bookmarks? – GrafiCode Dec 12 '19 at 17:19
  • 2
    Does this answer your question? [Why does a RegExp with global flag give wrong results?](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results) – GrafiCode Dec 12 '19 at 17:23
  • 2
    the MDN article epascarello linked details pretty much the same thing, if you need something to bookmark. There is also some documentation about regex's `lastIndex` in the articles for `exec`. – ASDFGerte Dec 12 '19 at 17:24
  • @ASDFGerte thanks, yes I also found another question here on SO with an excellent explaination – GrafiCode Dec 12 '19 at 17:24
  • Thanks for all your help ! – SH Kim Dec 12 '19 at 17:38

1 Answers1

0

The issue here is using test() with the global flag on a string advances the regex's lastIndex - even if you are testing a different string in a subsequent run.

Citing from the MDN: Using test() on a regex with the global flag

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property). It is worth noting that the lastIndex will not reset when testing a different string.

wp78de
  • 18,207
  • 7
  • 43
  • 71