Finding and Replacing Text


Another powerful text range technique is to use the findText method to search for text. Here's how that method works:

  TextRange  .findText(  text  [,  searchScope  ] [,  flags  ]) 

Here are the parameters you use with this method:

  • text . String that holds the text to find.

  • searchScope . Integer that holds the number of characters to search (starting from the start of the range). A positive integer results in a forward search, and a negative integer results in a backward search.

  • flags . Integer that holds a flag to indicate the type of search (see the following list.)

Here are the possible values for the flags parameteryou can OR these values together with the JavaScript bitwise OR operator, (see Chapter 2, "The JavaScript Language: Data, Operators, and Branching"), to specify more than one option (such as 2 4, which makes findText search for whole words only and match case):

  • The default. Matches partial words.

  • 1 Matches backward.

  • 2 Matches whole words only.

  • 4 Matches case.

  • 131072 Matches bytes.

  • 536870912 Matches diacritical marks.

  • 1073741824 Matches the Kashida character.

  • 2147483648 Matches the AlefHamza character.

This method returns true if the text you're searching for was found, and false otherwise . Here's an example. In this case, I'll search an entire document for the text Hi and replace it with the word Hello :

(Listing 11-02.html on the web site)
 <HTML>      <HEAD>          <TITLE>Finding text in text ranges</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function hi()              {  var range1 = document.body.createTextRange()   while(range1.findText("Hi")){   range1.text = "Hello"   }  }              // -->          </SCRIPT>      </HEAD>      <BODY ONLOAD="hi()">      <H1>Finding text in text ranges</H1>          <P>              He said, "Hi there!"          </P>      </BODY>  </HTML> 

You can see the results in Figure 11.2, where the code has replaced Hi with Hello as the page loaded.

Figure 11.2. Finding and replacing text with text ranges.

graphics/11fig02.gif



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