Skip navigation.

极湖

无不用其“极”

JavaScript: 判断字符串是否数字

一个小小的数字判断功能,也有很多学问。
请看解答: http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric

总结一下文章中提到的方法:

1. 内建函数 isNaN
这个不用多说。

2. 正则表达式
function isNumeric(x) {
   return /^-?\d*\.?\d+$/.test(x);
}


3. 利用类型变换
function isNumeric(x) {
    return parseFloat(x) == x;
}


4. 利用“潜规则”
function isNumeric(x) {
   return (x - 0) == x && x.length > 0;
}


Stackoverflow 上投票最多的竟然是利用“潜规则”的方法。看来,只有掌握了“潜规则”,才算真正精通一门语言。

文本编辑常用正则表达式(不定期更新)给 ExtJS 的输入控件增加提示功能

Write a comment

You must be logged in to write a comment. If you're not a registered member, please sign up.

November 2009
S M T W T F S
October 2009December 2009
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30