In JavaScript, you can use the Number() function and isNaN() function to determine whether a string is a number. The syntax is "isNaN(Number("String",10)"; if true is returned, then the The string is not a number, otherwise it is a number.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript determines whether a string is a number
In the process of converting a string into a number through Number(), if the string contains non-numbers, then Will return NaN, refer to the following code
Number("Hello",10);//return NAN Number("110",10);//return 110 Number("t2110",10);//return NAN Number("1f10g",10);//return NAN
So you can use isNaN() to determine whether the return value of Number() is NaN to determine whether the string is a number. If it returns true, the string is not a number, otherwise it is a number.
Implementation code:
function f(a){ if(isNaN(Number(a,10))){ console.log("不是数字"); } else{ console.log("是数字"); } }
Test:
f("hello"); f("10"); f("d10jh5"); f("10jh5");
Note: You cannot use the following method to judge:
Number("Hello",10)==NaN;//return false Number("110",10)==NaN;//return false
Because NaN and itself do not want to wait, this is quite special. The way to judge NaN is isNaN().
[Related recommendations: javascript learning tutorial 】
The above is the detailed content of How to determine whether a string is a number in javascript. For more information, please follow other related articles on the PHP Chinese website!