15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5 ✦ Body Text Objects (Chapter 19)<br />

Example<br />

Listing 19-11 implements two varieties of a text search-and-replace operation,<br />

while showing you how to include extra parameters for case-sensitive and whole<br />

word searches. Both approaches begin by creating a TextRange for the entire body,<br />

but they immediately shift the starting point to the beginning of the DIV element<br />

that contains the text to search.<br />

One search-and-replace function prompts the user to accept or decline replacement<br />

for each instance of a found string. The select() and scrollIntoView()<br />

methods are invoked to help the user see what is about to be replaced. Notice that<br />

even when the user declines to accept the replacement, the text range is collapsed<br />

to the end of the found range so that the next search can begin after the previously<br />

found text. Without the collapse() method, the search can get caught in an infinite<br />

loop as it keeps finding the same text over and over (with no replacement<br />

made). Because no counting is required, this search-and-replace operation is implemented<br />

inside a while repeat loop.<br />

The other search-and-replace function goes ahead and replaces every match and<br />

then displays the number of replacements made. After the loop exits (because<br />

there are no more matches), the loop counter is used to display the number of<br />

replacements made.<br />

Listing 19-11: Two Search and Replace Approaches<br />

(with Undo)<br />

<br />

<br />

TextRange.findText() Method<br />

<br />

// global range var for use with Undo<br />

var rng<br />

// return findText() third parameter arguments<br />

function getArgs(form) {<br />

var isCaseSensitive = (form.caseSensitive.checked) ? 4 : 0<br />

var isWholeWord = (form.wholeWord.checked) ? 2 : 0<br />

return isCaseSensitive ^ isWholeWord<br />

}<br />

// prompted search and replace<br />

function sAndR(form) {<br />

var srchString = form.searchString.value<br />

var replString = form.replaceString.value<br />

if (srchString) {<br />

var args = getArgs(form)<br />

rng = document.body.createTextRange()<br />

rng.moveToElementText(rights)<br />

clearUndoBuffer()<br />

while (rng.findText(srchString, 10000, args)) {<br />

rng.select()<br />

Continued<br />

305<br />

TextRange.findText()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!