JavaScript in-string variables
It is a pain in the ass to concatenate a ton of variables inside a string. This snippet replaces anything inside #{ and } with its content eval'ed. More instructions here.
String.prototype.pretify = function()
{
var matches = this.match(/\#\{.+?\}/g);
var pretified = this;
for (var m in matches)
{
var match = matches[m];
var evalCode = match.substr(2, match.length - 3);
var result = eval(evalCode);
pretified = pretified.replace(match, result);
}
return pretified;
};
Written by Fernando Santos
Related protips
8 Responses
I like it! I especially like that you extended the String prototype. Otherwise it would just be another template engine.
Hey im working on a prototype extension library. https://github.com/dperrymorrow/lil-p/blob/master/lil-p.js
Would you be interested in collaborating on this with me? The above String addition is really cool.
@dperrymorrow Thanks! Yes, I love prototype. Best thing since ever! :)
@dperrymorrow Sure, you can use this snippet. We can work together, although I don't have too much time, but we can talk, at least. Just throw me a message on GitHub.
Hmm, why not just use lodash.template? https://lodash.com/docs#template
It's a proven pattern & well tested
I would definitely miss this if I wouldn't use CoffeeScript. It doesn't even use eval, which can be potentially dangerous.
@pgilad It's an option. I've just made this out of fun some time ago :)
@zinkkrysty As of now, I don't even remember why the hell I've used "eval". Guess I was out of coffee.