Closed dijs closed 11 years ago
This is from Douglas Crawford's "Remedial Javascript". I thought I might help.
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;
}
);
};
// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));
I thought this was a clean way to approach the problem.
If I'm understanding you correctly, you're looking for string syntax like:
s = "I am #{50+1} years old"
Which is already supported. The supplant
thing is not supported right now (kind of like Python's old %
operator?), although you could do:
a = cow
n = moo
print "The #{a} says #{n}, #{n}, #{n}!"
Also, it only works with double quoted strings, not single quoted strings (on purpose like CoffeeScript).
Facepalm I had no idea this was already supported...
Is it in your documentation?
Technically yes, but it's just one little line in the readme (I agree it's not obvious at all). I'll add something more substantive.
Could this ever be a thing in Kal?
Obviously, it would be great to use variables also...