• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Matching Numbers

Another big use for regular expressions in JavaScript is to let you extract numbers (including dates, as we’ve already done in this chapter) from text. You can use the \d and \D assertions to check for digits, for example, to check user input to make sure that input is a number. The \D special character matches any character except digits, so you can check whether a string doesn’t represent a valid number this way:

(Listing 20-12.html on the web site)

<HTML> 
    <HEAD> 
        <TITLE>Checking Numbers</TITLE> 
        <SCRIPT LANGUAGE="JavaScript"> 
            <!--
            function checkNumber() 
            { 
                var regexp = /\D/ 

                var matches = regexp.exec(document.form1.text1.value)
					if (matches) {
					document.form1.text2.value = "That's not a number."
					} else {
					document.form1.text2.value = "OK."
					} 
            } 
            //--> 
        </SCRIPT> 
    </HEAD>  
    <BODY> 
        <H1>Checking Numbers</H1> 
        <FORM NAME="form1"> 
            Type a number: 
            <BR> 
            <INPUT TYPE="TEXT" NAME="text1"> 
            <BR> 
            <INPUT TYPE="BUTTON" VALUE="Check Number" ONCLICK="checkNumber()"> 
            <BR> 
            <INPUT TYPE="text" NAME="text2" SIZE="30"> 
        </FORM> 
    </BODY> 
</HTML> 

					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint