February 23, 2000 - IE 5.5's Enhanced replace() Function
![]() |
February 23, 2000 IE 5.5's Enhanced replace() Function Tips: February 2000
Yehuda Shiran, Ph.D.
|
replace()
function supports more features than version 5.0. In IE 5.0, the replace()
function uses two parameters: a regular expression and a replacement string. In
IE 5.5, the function uses two parameters as well, but the second one is a handling
function that utilizes the replacement in a more intensive manner. Let's take
an example.
We first define a regular expression:
var regExp = /(\w+)\s*(\w+)/g;
This regular expression will
match a string that includes a word, followed by a zero number or more of blanks,
and ends with a word. The flag /g
allows for more than one matches of the above sequence. The replace()
function uses two parameters: the regular expression and a handling function
(called here matchingFunction()).
Our matchingFunction()
is defined as:
function matchingFunction(matchedString, subMatch1, subMatch2, matchPos, source) {
return (subMatch1 + subMatch2)
}
A submatch is found according to the parenthesis in the regular expression. The first pair defines subMatch1, the second pair defines subMatch2, and so on. According to the regular expression above, the first pair encloses the first word and the second pair of parenthesis encloses the second word. For example, subMatch1 for Bill Clinton is Bill, while subMatch2 is Clinton. The parameter matchPos is the position within the source string that the match was found. The parameter source is the source string. The number of pairs of parenthesis in the regular expression must match the number of submatche parameters passed to the matchingFunction() above.
You can do anything inside the
matching function. At the end you have to return a string. In our case above,
we return a concatenation of the submatches. The replace()
function takes the string returned by the matching function and substitutes
it with the substring matched by the regular expression. In our case, the regular
expression matches the whole string of the president name, and the replace()
function replaces it with a concatenation of the first and last names.
Learn more about IE 5.5 in Column 57, The Doc Dialer, Part I.


Find a programming school near you