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

前端 未结 8 1355
粉色の甜心
粉色の甜心 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:49

    By using below function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javascript string as a parameter, then the function will return either true or false

    function hasNumbers(t)
    {
    var regex = /\d/g;
    return regex.test(t);
    }    
    
    0 讨论(0)
  • 2021-01-13 18:51

    You can always do:

    function isNumber(n)
    {
        if (n.trim().length === 0)
            return false;
        return !isNaN(n);
    }
    
    0 讨论(0)
  • 2021-01-13 18:52

    Let's try

    ""+(+n)===n
    

    which enforces a very rigid canonical way of the number.

    However, such number strings can be created by var n=''+some_number by JS reliable.

    So this solution would reject '.01', and reject all simple numbers that JS would stringify with exponent, also reject all exponential representations that JS would display with mantissa only. But as long we stay in integer and low float number ranges, it should work with otherwise supplied numbers to.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-13 18:59

    A very short, wrong but correctable answer was just deleted. I just could comment it, besides it was very cool! So here the corrected term again:

    n!=='' && +n==n'
    

    seems good. The first term eliminates the empty string case, the second one enforces the string interpretataion of a number created by numeric interpretation of the string to match the string. As the string is not empty, any tolerated character like whitespaces are removed, so we check if they were present.

    0 讨论(0)
  • 2021-01-13 19:00

    If you want something a little more complex regarding format, you could use regex, something like this:

    var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
    

    Demo

    enter image description here

    I created this regex while answering a different question awhile back (see here). This will check that it is a number with atleast one character, cannot start with 0 unless it is 0 (or 0.[othernumbers]). Cannot have decimal unless there are digits after the decimal, may or may not have commas.. but if it does it makes sure they are 3 digits apart, etc. Could also add a -? at the beginning if you want to allow negative numbers... something like:

    /^(-)?(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
    
    0 讨论(0)
提交回复
热议问题