1.7 Searching and Replacing SubstringsNN 4, IE 4 1.7.1 Problem
You want to perform a global
1.7.2 SolutionThe 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
1.7.3 Discussion
To work this regular expression mechanism into a practical function, you need some helpful
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
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
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
1.7.4 See AlsoSection 1.0.2 in the introduction to this chapter; Recipe 14.14 for additional body text replacement techniques in modern browsers. |
1.8 Using Special and Escaped
|
|
Escape sequence |
Description |
|---|---|
|
\b |
Backspace |
|
\t |
Horizontal tab |
|
\n |
Line feed (newline) |
|
\v |
Vertical tab |
|
\f |
Form feed |
|
\r |
Carriage return |
|
\" |
Double quote |
|
\' |
Single quote |
|
\\ |
Backslash |
Note that to include a visible backslash character in a string, you must use a double backslash because a single one is treated as the invisible escape character. Use the escaped quote symbols to include single or double quotes inside a string.
While you can use an escaped character in tests for the existence of, say, line feed characters in a string, you have to exercise some care when doing so with the content of a
textarea
element. The problem accrues from a variety of
Going the other way—creating a string for script insertion into a textarea value—is easier because modern browsers accommodate all symbols. Therefore, if you assign just \r or \n or the combination \r\n , all browsers interpret any one of them as a carriage return, and convert the escape character(s) to match their internal handling.
Recipe 1.1 for tips on concatenating strings—tips that apply equally to escaped string characters.