O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Automating the Search-and-Replace of Body Content

NN n/a, IE 4(Win)

Problem

You want to offer a search-and-replace function for body content.

Solution

This recipe works only in Internet Explorer 4 or later for Windows because of its heavy dependence upon the TextRange object (not implemented in IE/Mac through Version 5.x). On the plus side, it also works with textarea element content.

Use the rangeReplace.js library (Example 15-1 in the Discussion) to automate search and replace operations with the IE TextRange object. You have your choice of two functions, depending on the type of search-and-replace user experience you prefer. Invoke the srBatch( ) function for unprompted batch replacement:

srBatch(document.body, "Law", "legislation", false, false);

The five parameters specify:

  • A reference to the element to become the text range

  • A string to search for

  • A string to replace found strings

  • A Boolean for case-sensitive search

  • A Boolean for whole-word matches

The companion srQuery( ) function takes the same set of arguments, but highlights each match, and prompts the user to confirm each replacement:

srQuery(document.body, "Law", "legislation", false, false);

To undo the replacements performed by the last invocation of either function, invoke the undoReplace( ) function with no arguments.

Discussion

Example 15-1 shows the rangeReplace.js library. Link it into any document that requires this functionality.

Example 15-1. The rangeReplace.js library

// Global range object variable var rng; // ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required