/** 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 ist zweifellos ein JavaScript Grand Wizard, aber sein Prototyp fehlt, wenn es um Objekte mit mehreren Ebenen geht.
Ich möchte, dass diese Funktion das Ersetzen von Objekten auf mehreren Ebenen abdeckt, z. B. '{post.detailed}'. Kann mir jemand bei einer überarbeiteten Version des Ersatzes helfen?
3 Antworten
Das sollte nicht zu schwierig sein. Verwenden Sie stattdessen diese Ersetzungsfunktion:
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;
}
Ich persönlich hasse es, wenn Leute ihren eigenen Müll auf die nativen Typen in JavaScript stopfen. Wenn ich es schreiben würde, würde ich Folgendes tun ... Aber warum keine Liebe zum Booleschen?
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;
});
};
Arrays werden übrigens nicht unterstützt, Sie müssten einige zusätzliche Dinge tun, um dies zu unterstützen.
@Bergi-Methode mit Unterstützung für Boolesche Werte:
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 Crockfords Supplant-Methode mit Unterstützung für Boolesche Werte:
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;
}
);
};
}
Viel Glück!
https://gist.github.com/fsschmitt/b48db17397499282ff8c36d73a36a8af