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

前端 未结 4 2003
挽巷
挽巷 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-27 23:58

    * means 0 or more, so it's matching 0 times. You need to use + for 1 or more. By default it's greedy, so will match 100:

    var str = 'one to 100';
    var regex = /\d+/;
    console.log(str.match(regex));
    // ["100"]
    

提交回复
热议问题