How to use template string in Javascript?

Asked

Viewed 8,429 times

9

I’m having trouble making a Javascript function that I pass a string and an object and it fills this string with the attributes of that object, for example:

var user = {
    nome: "danilo", 
    idade: 29
};
var a = "Meu nome é ${nome}, e tenho ${idade} anos";
  • 1

    This plugin does just what you are trying to implement: http://www.jsviews.com

  • did not want to add another plugin in the project to accomplish something so simple, even so thank you.

  • I understand, until pq Jsviews will only be really useful if you need to create a more complex template, conditions, loops, complex templates, etc.

4 answers

16

Using the calls Template Strings, available as one of the modules of Ecmascript 2015 (ES6) and that should soon enter all browsers (already available in Firefox), you could do so:

var user = {
    nome: "danilo", 
    idade: 29
};
var a = `Meu nome é ${user.nome}, e tenho ${user.idade} anos`;

Or else:

with(user) {
    a = `Meu nome é ${nome}, e tenho ${idade} anos`;
}

Note that inverted quotes were used to enclose this string, since this is the syntax that should be used when working with template strings.

12


Javascript currently implemented in browsers does not support string Interpolation,. You gotta do it like this:

"Meu nome é " + nome + ", e tenho " + idade + " anos"

Or use the function created by Douglas Crockford:

String.prototype.concatenar = (a) => this + a;

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

console.log("Meu nome é ${nome}, e tenho ${idade} anos".supplant({ nome: "danilo", idade : 29 }));

I put in the Github for future reference.

  • Solved my problem without having to install any additional lib. Excellent! I was wondering just how this "String.prototype" works, is an extension? Where do I read more about it?

  • The prototype is in every object. http://answall.com/search?q=%5Bjavascript%5D+prototype

6

ES2015 already has its own template string structure, but while we don’t have compatibility across all browsers, you can use something like this:

var data = {
    host: 'twitter.com',
    port: '80',
    user: 'henricavalcante'
};

var a = "http://${host}:${port}/${user}";

var c = a.split('$').map(function(a) {
    if (a.substr(0,1) !== '{') {
        return a;
    }
    var key = a.substring(1,a.indexOf('}'));
    return a.replace('{'+key+'}', data[key]);
}).join('');

console.log(c); // http://twitter.com/henricavalcante

-1

Vanilla JS:

String.prototype.format = function (args) {
    var text = this
    for(var attr in args){
        text = text.split('${' + attr + '}').join(args[attr]);
    }
    return text
};

json = {'who':'Gendry', 'what':'will sit', 'where':'in the Iron Throne'}
text = 'GOT: ${who} ${what} ${where}';

console.log('context: ',json);
console.log('template: ',text);
console.log('formated: ',text.format(json));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.