Matching Numbers


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> 

You can see the results of this code in Figure 20.9.

Figure 20.9. Checking for valid numbers.

graphics/20fig09.gif

The \d special character matches individual digits, as in this pattern that matches dates in the form 12/31/1960 that we've already seen:

 var regexp = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/ 

You also can create custom formats. For example, you may want to handle numbers of at least one digit followed by a decimal point and some optional digits after the decimal point. Here's how that would look:

 var regexp =  /^\d+\.\d*$/ 

What about numeric signs, such as + or -? You can handle those with a character class:

 var regexp = /^[+-]\d+\.\d*$/ 

Want to match hexadecimal numbers? Try this one:

 var regexp = /^[\da-f]+$/i 


Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net