1.7 Searching and Replacing Substrings

NN 4, IE 4

1.7.1 Problem

You want to perform a global search-and-replace operation on a text string.

1.7.2 Solution

The most efficient way (for NN 4 or later and IE 4 or later) is to use a regular expression with the replace( ) method of the String object:

var re = /a string literal/g;
var result = mainString.replace(re, replacementString);

Invoking the replace( ) method on a string does not change the source string. Capture the changed string returned by the method, and apply the result where needed in your scripts or page. If no replacements are made, the original string is returned by the method. Be sure to specify the g modifier for the regular expression to force the replace( ) method to operate globally on the original string; otherwise, only the first instance is replaced.

1.7.3 Discussion

To work this regular expression mechanism into a practical function, you need some helpful surrounding code. If the string you are looking for is in the form of a string variable, you can't use the literal syntax for creating a regular expression as just shown. Instead, use the constructor function:

var searchStr = "F2";
var replaceStr = "Framistan 2000";
var re = new RegExp(searchStr , "g");
var result = longString.replace(re, replaceStr);

In working with a text-based form control or an element's text node, you can perform the replace( ) operation on the value of the existing text, and immediately assign the results back to the original container. For example, if a div element contains one text node with scattered place holders in the form of (ph), and the job of the replace( ) method is to insert a user's entry from a text box (called myName), the sequence is as follows:

var searchStr = "\\(ph\\)";
var re = new RegExp(searchStr, "g");
var replaceStr = document.myForm.myName.value;
var div = document.getElementById("boilerplate");
div.firstChild.nodeValue = div.firstChild.nodeValue.replace(re, replaceStr);

The double backslashes are needed to escape the escape character before the parentheses characters, which are otherwise meaningful symbols in the regular expression pattern language.

It is also possible to implement a search-and-replace feature without regular expressions but it's a cumbersome exercise. The technique involves substantial text parsing using the indexOf( ) method to find the starting location of text to be replaced. You need to copy preceding text into a variable and strip away that text from the original string; keep repeating this find-strip-accumulate tactic until the entire string is accounted for, and you have inserted the replacement string in place of each found search string. It was necessary in the early browsers, but regular expressions are implemented in almost all scriptable browsers that are now in use.

1.7.4 See Also

Section 1.0.2 in the introduction to this chapter; Recipe 14.14 for additional body text replacement techniques in modern browsers.