Check if a variable contains a numerical value in Javascript?

后端 未结 9 1469
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 18:36

In PHP, it\'s pretty easy:

is_numeric(23);//true
is_numeric(\"23\");//true
is_numeric(23.5);//true
is_numeric(true);//false

But how do I do

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 19:30

    This checks for numerical values, including negative and floating point numbers.

    function is_numeric(val){
        return val && /^-?\d+(\.\d+)?$/.test(val + '');
    }
    

    @Vordreller: I corrected the Regex. It should work properly now.

提交回复
热议问题