Why javascript string match includes undefined

前端 未结 4 1440
有刺的猬
有刺的猬 2020-12-20 15:46

I have a regex that is more or less used like this:

\'(801) 555-1234\'.match(/^(1[-. ]?)?\\(?[0-9]{3}\\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/)

Fo

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 16:23

    It's because your regex starts with that parenthesized group. The undefined in the result means that nothing matched that part.

    When you add the "g" suffix, the behavior of the regex code changes a little, so the return value is different. The "g" ("global") suffix causes the routine to return all the matches of the whole regex; the groups are effectively ignored in that case. For example:

    "hello world! nice day today!".match(/\w+/g)
    

    would return an array like this:

    ["hello", "world", "nice", "day", "today"]
    

提交回复
热议问题