Chapter 20. The RegExp Object: Working with Regular Expressions


Chapter 20. The RegExp Object: Working with Regular Expressions

graphics/chic01.gif

One of the powerful aspects of JavaScript is its capability to work with text. Ever since Internet Explorer 4.0 and Netscape Navigator 4.0, that has been augmented by being able to work with regular expressions . Regular expressions enable you to handle not only text strings as variables , but also work with the text content of those strings.

Using a regular expression, you can specify what kind of text substrings you want to match and work with. For example, here's how I'm using the regular expression /[aeiou]/ to search text in a text field for vowels, and if any vowels are found, to display the message Yes, we got vowels! in a text field:

(Listing 20-01.html on the web site)
 <HTML>      <HEAD>          <TITLE>Checking for Vowels</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function checkVowels()              {  var regexp = /[aeiou]/   var matches = regexp.exec(document.form1.text1.value)   if (matches) {   document.form1.text2.value = "Yes, we got vowels!"   } else {   document.form1.text2.value = "Sorry, no vowels!"   }  }              //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>Checking for Vowels</H1>          <FORM NAME="form1">              Type some text:              <BR>              <INPUT TYPE="TEXT" NAME="text1">              <BR>              <INPUT TYPE="BUTTON" VALUE="Check for Vowels" ONCLICK="checkVowels()">              <BR>              <INPUT TYPE="text" NAME="text2" SIZE="30">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 20.1, where the code has determined that there are indeed vowels present.

Figure 20.1. Checking for vowels.

graphics/20fig01.gif

This chapter shows you how to work with regular expressions such as /[aeiou]/ in JavaScript. There are two primary ways to use regular expressions: to find matches and to replace text. I'll cover both of them first, and then we'll take a look at how to create regular expressions themselves (which can get pretty involved).



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