ArticleDirectory
Javascript judgment number
JavaScript does not directly determine whether it is a numeric function. When I program to flip pages, I need to determine whether the user input is a number,
I can see such a judgment function on the Internet:
// Determine the number
Function isdigit (thenum)
{
VaR themask = "0123456789 ";
If (isempty (thenum) Return (false );
Else if (themask. indexof (thenum) =-1) Return (false );
Return (true );
}
At that time, I did not go deep into it and found it could be used. It turns out that it is inaccurate because the number is better than 10, and it is incorrect if the number is greater than 10.
The indexof function is actually a function for finding substrings, so it is obvious that the aboveProgramNo. The Internet also uses loops to determine whether a number is counted at a time based on the length. However, I always feel so annoying and inefficient. The following may be simple and efficient:
Function isdigit (s)
{
VaR R, RE;
Re =/\ D */I; // \ D indicates a number, and * Indicates matching multiple numbers.
R = S. Match (re );
Return (r = s )? 1:0;
}
Try to see:
<HTML>
<Body>
<Script language = JavaScript>
Function isdigit (s)
{
VaR R, RE;
Re =/\ D */I; // \ D indicates a number, and * Indicates matching multiple numbers.
R = S. Match (re );
Return (r = s )? 1:0;
}
VaR S1 = "123 ";
VaR S2 = "45a ";
VaR S3 = "BCD ";
VaR S4 = "E6"
Alert ("S1 =" + isdigit (S1) + "R2 =" + isdigit (S2) + "R3 =" + isdigit (S3) + "r4 =" + isdigit (S4 ));
</SCRIPT>
</Body>
</Html>
It seems that the judgment is correct. Pretty good.
For functions with direct judgment by tkote, isnan