Previous Example-|-Next Example-|-Return to Chapter Listing

Example 14.18:
Regular Expressions - Remembering the Matched Expression

[This example works with Netscape Navigator 4. It won't work with Netscape Navigator 2 or 3, or Internet Explorer 3.]

This script remembers what it finds. Type a phone number into the text box; use groups of 3, 3, and 4 characters, and any other non-digit characters you want (303) 555-1234, for instance, or 303+555+1234, or even 303x555x1234. The script will extract the phone number and display it in an alert box.


Here's the function: <SCRIPT language="JavaScript"> <!-- function phoneNumber(form) { var s = form.data.value var num = new Array() var p = /(\d{3})\D*(\d{3})\D*(\d{4})/ num = s.match(p) alert("The phone number is " + num) } // --> </SCRIPT> Here's the form: <FORM name="matchForm"> Enter some text: <INPUT type="text" name="data" size=80 value="This is a test. You can enter other text here."><P> <INPUT type="button" Value="Do the match" onclick="matchIt(this.form)"><P> Results (the number of characters found): <INPUT type="text" name="results" size=40><P> </FORM>
Previous Example-|-Next Example-|-Return to Chapter Listing