(Built-in) way in JavaScript to check if a string is a valid number

前端 未结 30 3366
-上瘾入骨i
-上瘾入骨i 2020-11-22 01:54

I\'m hoping there\'s something in the same conceptual space as the old VB6 IsNumeric() function?

30条回答
  •  广开言路
    2020-11-22 02:37

    In my application we are only allowing a-z A-Z and 0-9 characters. I found the answer above using " string % 1 === 0" worked unless the string began with 0xnn (like 0x10) and then it would return it as numeric when we didn't want it to. The following simple trap in my numeric check seems to do the trick in our specific cases.

    function isStringNumeric(str_input){   
        //concat a temporary 1 during the modulus to keep a beginning hex switch combination from messing us up   
        //very simple and as long as special characters (non a-z A-Z 0-9) are trapped it is fine   
        return '1'.concat(str_input) % 1 === 0;}
    

    Warning : This might be exploiting a longstanding bug in Javascript and Actionscript [Number("1" + the_string) % 1 === 0)], I can't speak for that, but it is exactly what we needed.

提交回复
热议问题