How to check if a string contains a number in JavaScript?

前端 未结 8 1369
粉色の甜心
粉色の甜心 2021-01-13 18:37

I don\'t get how hard it is to discern a string containing a number from other strings in JavaScript.

Number(\'\') evaluates to 0, while

8条回答
  •  天涯浪人
    2021-01-13 18:57

    There's this simple solution :

    var ok = parseFloat(s)==s;
    

    If you need to consider "2 " as not a number, then you might use this one :

    var ok = !!(+s==s && s.length && s.trim()==s);
    

提交回复
热议问题