Why does String.match( / \d*/ ) return an empty string?

前端 未结 4 1992
挽巷
挽巷 2020-11-27 23:34

Can someone help me to understand why using \\d* returns an array containing an empty string, whereas using \\d+ returns [\"100\"] (as expected). I get why the \\d+ works, b

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 00:16

    Remember that match is looking for the first substring it can find that matches the given regex.

    * means that there may be zero or more of something, so \d* means you're looking for a string that contains zero or more digits.

    If your input string started with a number, that entire number would be matched.

    "5 to 100".match(/\d*/); // "5"
    "5 to 100".match(/\d+/); // "5"
    

    But since the first character is a non-digit, match() figures that the beginning of the string (with no characters) matches the regex.

    Since your string doesn't begin with any digits, an empty string is the first substring of your input which matches that regex.

提交回复
热议问题