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 Matches
The function passes a dictionary in as o, and performs a replace using the regex above. Whenever there is a match, the callback function of the replace will be invoked. a is the whole matched part, and b is the submatch part corresponding to the "Parenthesized Substring Matches". The callback function looks for b as the key in the dictionary, and return the corresponding value
the return statement means if the type of r is string or number, then return r; otherwise return a
You can checkout the example code provided by Jared Farrish, which shows how the match and replace work very clearly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With