开发者

Javascript regex that matches a decimal that is polluted with other characters

I'm trying to match the first set of digits in the following examples.

some stuff (6 out of 10 a开发者_Go百科s a rating) 

needs to return 6

some stuff (2.3 out of 10 as a rating)    

needs to return 2.3

some stuff (10 out of 10 as a rating)  

needs to return 10

Also, sometimes the string won't have a number

some stuff but nothing else


var match = /\d+(\.\d+)?/.exec("some stuff (10 out of 10 as a rating)");
alert(match[0]);
  • \d matches any numner, 0-9
  • + means 1 or more
  • \. matches a .
  • ? means 0 or 1

so overall it means any number of digits (0-9) optionally followed by, a decimal point followed by 1 or more digits.

As a function:

var getFirstNumber = function(input){
     var match = /\d+(\.\d+)?/.exec(input);
    return match[0];
};


You can try this 'some stuff (2.3 out of 10 as a rating)'.match(/\D*(\d\.?(\d)*)/)[1]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜