faqts : Computers : Programming : Languages : JavaScript : Language Core : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 24 people (75%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Is it possible to use string.replace() with a function in the replace string in IE5+?

Apr 22nd, 2003 22:34
Mark Szlazak, Nunya Business, JavaScript The Definitive Guide - 4th Ed. pp 526, 527.


SYNOPSIS
string.replace(regexp, replacement)
DESCRIPTION
ECMAScript v3 specifies that the "replacement" argument to replace() 
may be a function instead of a string, and this feature is implemented 
in JavaScript 1.2 and JScript 5.5+. In this case, the function is 
invoked for each match and the string it returns is used as the 
replacement text. The first argument to the function is the string that 
matched the pattern. The next arguments are the strings that matched 
any parenthesized subexpressions within the pattern. There may be zero 
or more of these arguments. The next argument is an integer that 
specifies the position within "string" at which the match occurred, and 
the final argument to the "replacement" function is the "string" itself.
EXAMPLE
To capitalize the first letter of all words in a string:
    text.replace(/\b\w+\b/g, function(word) {
                               return word.substring(0,1).toUpperCase()
+ word.substring(1);
                             });