Replacing Text


Besides searching for matches to regular expressions, you also can use them to replace text, using the String object's replace method:

  • The String object's replace method. This method replaces substrings with a new string. Syntax: string.replace( regExp , replacementText ) ; where regExp is a regular expression, and replacementText replaces matches to regExp . (All matches are replaced if regExp includes the g modifier.) See Chapter 18 for more information.

We saw an example of this method in Chapter 18. In that example, we searched for the text is in the phrase "Now is the time" and replaced it with the text isn't . Here's what the code looked like (Listing 18-11.html on the web site ); the g modifier in the regular expression makes the search-and-replace operation global, which makes it match all occurrences of is in the searched string:

 <HTML>      <HEAD>          <TITLE>              Replacing Text          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function replacer()   {   var regExp = /is/g   var text = document.form1.text1.value.replace(regExp, "isn't")   document.form1.text1.value = text   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Replacing Text</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" VALUE="Now is the time">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="replacer()" VALUE="Replace Text">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Chapter 18, in Figure 18.11, where we've changed "Now is the time" to "Now isn't the time" .

Those are the two ways to use regular expressions in JavaScript: to search text and to replace text. However, the actual syntax of regular expressions is still mysterious at this point. How on earth do you actually createmuch less understandan expression such as /^(0?[1-9] 1[0-2])\/(0? [1-9] [12][0-9] 3[01])\/((18 19 20)\d{2})$/ ? I'll take a look at how you create regular expressions now.



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