/** 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;
}
);
};
Crockford is no doubt a JavaScript Grand Wizard, but his prototype is lacking when it comes to multiple level objects.
I would like this function to cover multiple level object replacement such as '{post.detailed}' could anyone help me with a revised version of supplant?
That shouldn't be too difficult. Use this replace function instead:
function (a, b) {
var r = o,
parts = b.split(".");
for (var i=0; r && i<parts.length; i++)
r = r[parts[i]];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
I personally hate it when people stuff their own rubbish on the native types in JavaScript. If I were to write it I would do the following... But why no love for boolean?
function supplant(str, data) {
return str.replace(/{([^{}]*)}/g, function (a, b) {
// Split the variable into its dot notation parts
var p = b.split(/\./);
// The c variable becomes our cursor that will traverse the object
var c = data;
// Loop over the steps in the dot notation path
for(var i = 0; i < p.length; ++i) {
// If the key doesn't exist in the object do not process
// mirrors how the function worked for bad values
if(c[p[i]] == null)
return a;
// Move the cursor up to the next step
c = c[p[i]];
}
// If the data is a string or number return it otherwise do
// not process, return the value it was, i.e. {x}
return typeof c === 'string' || typeof c === 'number' ? c : a;
});
};
It doesn't support arrays btw, you would need to do some additional stuff to support that.
@Bergi method w/ support to boolean:
function (a, b) {
var r = o,
parts = b.split(".");
for (var i=0; r && i<parts.length; i++)
r = r[parts[i]];
return typeof r === 'string' || typeof r === 'number' || typeof r === 'boolean' ? r : a;
}
Original Crockford's Supplant method w/ support to boolean:
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' || typeof r === 'boolean' ? r : a;
}
);
};
}
Best of luck!
https://gist.github.com/fsschmitt/b48db17397499282ff8c36d73a36a8af
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