# replaceWithCallback() UDF

As explained in my blog article

I was looking up the docs for Javascript's String replace() function the other day (because, no, I could not remember the vagaries of its syntax!). And whilst being relieved I had remembered it correctly for my immediate requirements, I also noticed it can take a callback instead of a string for its replacement argument. How cool is that?

I figured this could be handy for CFML's reReplace() function too, so decided to look at how it would work before raising the enhancement request, and in the process wrote a reasonable UDF which does the business, by way of proof of concept.

I'll submit replaceWithCallback() to CFLib, but I am wary of self-approving stuff, so I'll get you lot to cast yer eyes over it too, by way of community driven code review.

/**
@hint Analogous to reReplace()/reReplaceNoCase(), except the replacement is the result of a callback, not a hard-coded string
@string The string to process
@regex The regular expression to match
@callback A UDF which takes arguments match (substring matched), found (a struct of keys pos,len,substring, which is subexpression breakdown of the match), offset (where in the string the match was found), string (the string the match was found within)
@scope Number of replacements to make: either ONE or ALL
@caseSensitive Whether the regex is handled case-sensitively
*/
string function replaceWithCallback(required string string, required string regex, required any callback, string scope="ONE", boolean caseSensitive=true){
if (!isCustomFunction(callback)){ // for CF10 we could specify a type of "function", but not in CF9
throw(type="Application", message="Invalid callback argument value", detail="The callback argument of the replaceWithCallback() function must itself be a function reference.");
}
if (!isValid("regex", scope, "(?i)ONE|ALL")){
throw(type="Application", message="The scope argument of the replaceWithCallback() function has an invalid value #scope#.", detail="Allowed values are ONE, ALL.");
}
var startAt    = 1;

while (true){    // there's multiple exit conditions in multiple places in the loop, so deal with exit conditions when appropriate rather than here
if (caseSensitive){
var found = reFind(regex, string, startAt, true);
}else{
var found = reFindNoCase(regex, string, startAt, true);
}
if (!found.pos[1]){ // ie: it didn't find anything
break;
}
found.substring=[];    // as well as the usual pos and len that CF gives us, we're gonna pass the actual substrings too
for (var i=1; i <= arrayLen(found.pos); i++){
found.substring[i] = mid(string, found.pos[i], found.len[i]);
}
var match = mid(string, found.pos[1], found.len[1]);
var offset = found.pos[1];

var replacement = callback(match, found, offset, string);

string = removeChars(string, found.pos[1], found.len[1]);
string = insert(replacement, string, found.pos[1]-1);

if (scope=="ONE"){
break;
}
startAt = found.pos[1] + len(replacement);
}
return string;
}


Tests / samples:

function reverseEm(required string match, required struct found, required numeric offset, required string string){
return reverse(match);
}

input = "abCDefGHij";
result = replaceWithCallback(input, "[a-z]{2}", reverseEm, "ALL", true);
writeOutput(input & "<br>" & result & "<br><hr>");

function oddOrEven(required string match, required struct found, required numeric offset, required string string){
var oddOrEven = match MOD 2 ? "odd" : "even";
return match & " (#oddOrEven#)";
}

input = "1, 6, 12, 17, 20";
result = replaceWithCallback(input, "\d+", oddOrEven, "ALL", true);
writeOutput(input & "<br>" & result & "<br><hr>");

function messWithUuid(required string match, required struct found, required numeric offset, required string string){
var firstEight            = reverse(found.substring[2]);
var nextFour            = lcase(found.substring[3]);
var secondSetOfFour        = "<strong>" & found.substring[4] & "</strong>";
var lastBit                = reReplace(found.substring[5], "\d", "x", "all");

return "#firstEight#-#nextFour#-#secondSetOfFour#-#lastBit#";
}

input = "#createUuid()#,XXXXXXXXX-XXXX-XXXX-XXXXXXXXXXXXXXXX,#createUuid()#";
result = replaceWithCallback(input, "([0-9A-F]{8})-([0-9A-F]{4})-([0-9A-F]{4})-([0-9A-F]{16})", messWithUuid, "ALL", true);
writeOutput(input & "<br>" & result & "<br><hr>");

• I find it odd that you don't scope your arguments, any reason for that? Jul 18 '13 at 21:48
• Hi @Busches, good observation. I wrote up my position on this on my [blog][1]. Thanks for the inspiration for the article. Bottom line: I think the code is clearer that way. [1]: cfmlblog.adamcameron.me/2013/07/scoping-or-not-scoping.html Jul 25 '13 at 12:43

If the idea is to model this function on JavaScript's String.replace(), then there is a "bug". In JavaScript, when doing a global replace, the last argument passed to the callback is always the original unmodified string, not the string that may have had some of the replacements already applied to it, which is what you've written. The same should be true of the offsets passed to the callback: they should indicate the original positions.

Keeping in mind that I'm a complete newbie to CFML… I'd make a few minor tweaks to the loop.

By converting while (true) { … } to do { … } while (scope == "ALL");, you can avoid one of the inelegant break; statements.

When defining match, you can just reuse found.substring[1], and save a call to mid().

In the following few lines, you can reuse offset instead of found.pos[1] for a slight improvement in readability.

var lengthDiff = 0;
var origString = string;
do {
var found = caseSensitive ? REFind(regex, string, startAt, true)
: REFindNoCase(regex, string, startAt, true);
if (!found.pos[1]) { // ie: it didn't find anything
break;
}
found.substring=[];    // as well as the usual pos and len that CF gives us, we're gonna pass the actual substrings too
for (var i=1; i <= arrayLen(found.pos); i++){
found.substring[i] = mid(string, found.pos[i], found.len[i]);
}
var match = found.substring[1];
var offset = found.pos[1];
var length = found.len[1];

var replacement = callback(match, found, offset - lengthDiff, origString);
string = removeChars(string, offset, length);
string = insert(replacement, string, offset-1);

lengthDiff += len(replacement) - length;
startAt = offset + len(replacement);
} while (scope == "ALL");

• Nice one! Thanks for spotting the bug and my brain fart in re-calling mid(). Also nice adjustment with the loop exit condition: much cleaner. Nov 29 '14 at 11:08