Issues with a lambda expression
In javascript you can use a function to as an argument to the string.replace function when matching against a regex pattern - this is often referred to as a lambda expression. For example, in the following piece of code, the function is invoked for each match. The result is that the letters in the word "foo" are alerted in sequence:
var myString = "foo" ; var rex = /(\w)/gi ; var tempStrng = myString.replace( rex, function( $1 ) { alert( "current letter is: " + $1 ) ; return $1 ; } ) ;
Recently on a regex list a question arose where a person was having issues with inconsistencies when attempting to replace using this behaviour. (At least) Part of the problem was due to the fact that the person was referencing the matched text by prepending the $ matches with the RegExp object, like so:
var tempStrng = myString.replace( rex, function( RegExp.$1 ) { alert( "current letter is: " + RegExp.$1 ) ; return RegExp.$1 ; } ) ;
From my tests it appears that the global Regexp.$1 is not updated until *after* the function call and that, to refer to the matches inline you have to refer to the local copy $0...$n.
To see what I mean, try running the following code.
function alertme( val )
{
alert( "Iteration #" + i + " --> " + val ) ;
return val ;
}
var data = ["aaaa", "bbbb", "ccccc", "dddd"] ;
re = /(\w+)/gi ;
for( var i = 0 ; i < data.length ; i++ )
{
var temp = data[i].replace( re,
function( $1 )
{
alertme( $1, i ) ;
}
) ;
}
alert( "Now running the tests against RegExp object" ) ;
// notice how the alerted value is always 1 value *behind*
for( var i = 0 ; i < data.length ; i++ )
{
var temp = data[i].replace( re,
alertme( RegExp.$1 )
) ;
}