Last Updated: February 25, 2016
·
1.711K
· nandobang

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;
};

8 Responses
Add your response

I like it! I especially like that you extended the String prototype. Otherwise it would just be another template engine.

over 1 year ago ·

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.

over 1 year ago ·

@dperrymorrow Thanks! Yes, I love prototype. Best thing since ever! :)

over 1 year ago ·

@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.

over 1 year ago ·

Hmm, why not just use lodash.template? https://lodash.com/docs#template
It's a proven pattern & well tested

over 1 year ago ·

I would definitely miss this if I wouldn't use CoffeeScript. It doesn't even use eval, which can be potentially dangerous.

over 1 year ago ·

@pgilad It's an option. I've just made this out of fun some time ago :)

over 1 year ago ·

@zinkkrysty As of now, I don't even remember why the hell I've used "eval". Guess I was out of coffee.

over 1 year ago ·