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

前端 未结 9 821

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"].

提交回复
热议问题