In our daily work, we use javaScript to determine whether a string contains numbers and "-". In some form submission places, this is a more useful general judgment. There are several different methods collected here
1. Regular expression method to determine whether it is a number, including determining a positive integer:
##
function checkRate(input) { var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字,//若判断正整数,则后边是:/^[1-9]+[0-9]*]*$/ if (!re.test(input.rate.value)) { alert("请输入数字(例:0.02)"); input.rate.focus(); return false; } }
2. Ordinary JS function method:
function BASEisNotNum(theNum) { if (BASEtrim(theNum)=="") return true; for(var i=0;i<theNum.length;i++){ oneNum=theNum.substring(i,i+1); if (oneNum<"0" || oneNum>"9") return true; } return false; }
3. Determine whether it is a positive number, that is Positive integer:
function BASEisNotInt(theInt) { theInt=BASEtrim(theInt); if ((theInt.length>1 && theInt.substring(0,1)=="0") || BASEisNotNum(theInt)){ return true; } return false; }
4. Determine whether the string is composed of numbers and other symbols, such as "-":
function ismonth(str) { for(ilen=0;ilen<str.length;ilen++) { if(str.charAt(ilen) < '0' || str.charAt(ilen) > '9' ) { if((str.charAt(ilen)!='-')) return false; } } return true; }
5. Determine whether it is a floating point number:
function BASEisNotFloat(theFloat) { len=theFloat.length; dotNum=0; if (len==0) return true; for(var i=0;i<len;i++){ oneNum=theFloat.substring(i,i+1); if (oneNum==".") dotNum++; if ( ((oneNum<"0" || oneNum>"9") && oneNum!=".") || dotNum>1) return true; } if (len>1 && theFloat.substring(0,1)=="0"){ if (theFloat.substring(1,2)!=".") return true; } return false;
isNaN(expression:Object) : Boolean. Computes a parameter and returns true if the value is NaN (not a number). This function can be used to check whether a mathematical expression evaluates successfully to a number.
is often used like this in submission forms:
<script> if(isNaN(document.login.imgcode.value)){ alert('验证码不是数字!') document.login.imgcode.focus(); return false; } </script>
The above is the detailed content of How to determine if a js string contains numbers and special characters?. For more information, please follow other related articles on the PHP Chinese website!