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:
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):
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.
|