What is the meaning of the 'g' flag in regular expressions?

前端 未结 9 702

What is the meaning of the g flag in regular expressions?

What is is the difference between /.+/g and /.+/?

相关标签:
9条回答
  • 2020-11-22 10:08
    1. g -> returns all matches
    2. without g -> returns first match

    example:

    1. '1 2 1 5 6 7'.match(/\d+/) returns ["1", index: 0, input: "1 2 1 5 6 7", groups: undefined]. As you see we can only take first match "1".
    2. '1 2 1 5 6 7'.match(/\d+/g) returns an array of all matches ["1", "2", "1", "5", "6", "7"].
    0 讨论(0)
  • 2020-11-22 10:10

    G in regular expressions is a defines a global search, meaning that it would search for all the instances on all the lines.

    0 讨论(0)
  • 2020-11-22 10:11

    g is the global search flag.

    The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern.

    So the difference between /.+/g and /.+/ is that the g version will find every occurrence instead of just the first.

    0 讨论(0)
提交回复
热议问题