I recently came across the Javascript supplant function by crockford. The function goes like this –
if (!String.prototype.supplant) {
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
}
I need to understand the mechanics of this function and how exactly is this thing working. I have come across many explanations but all tend to make things complex by introducing technicalities that make things worse.
Trying to look for
1.The regex explanation here
2.the logic for the function(a,b) code block
3.the use of that return statement
as Tomalak said, spaces in regex are not trivial
the regex basically matchs something like this:
{ ... }. the[^{}]means the content in the curly braces can be anything but curly nraces. The*means the length of the content can be zero or any number. The part inside the parentheses is Parenthesized Substring MatchesThe function passes a dictionary in as
o, and performs areplaceusing the regex above. Whenever there is a match, the callback function of thereplacewill be invoked.ais the whole matched part, andbis the submatch part corresponding to the “Parenthesized Substring Matches”. The callback function looks forbas the key in the dictionary, and return the corresponding valuethe return statement means if the type of
ris string or number, then returnr; otherwise returnaYou can checkout the example code provided by Jared Farrish, which shows how the match and replace work very clearly.