Javascript judgment number

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.