How to interpolate variables in strings in JavaScript, without concatenation?

前端 未结 16 2232
长情又很酷
长情又很酷 2020-11-22 02:41

I know in PHP we can do something like this:

$hello = \"foo\";
$my_string = \"I pity the $hello\";

Output: \"I pity the foo\"<

相关标签:
16条回答
  • 2020-11-22 03:04

    Don't see any external libraries mentioned here, but Lodash has _.template(),

    https://lodash.com/docs/4.17.10#template

    If you're already making use of the library it's worth checking out, and if you're not making use of Lodash you can always cherry pick methods from npm npm install lodash.template so you can cut down overhead.

    Simplest form -

    var compiled = _.template('hello <%= user %>!');
    compiled({ 'user': 'fred' });
    // => 'hello fred!'
    

    There are a bunch of configuration options also -

    _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
    var compiled = _.template('hello {{ user }}!');
    compiled({ 'user': 'mustache' });
    // => 'hello mustache!'
    

    I found custom delimiters most interesting.

    0 讨论(0)
  • 2020-11-22 03:08

    Simply use:

    var util = require('util');
    
    var value = 15;
    var s = util.format("The variable value is: %s", value)
    
    0 讨论(0)
  • 2020-11-22 03:10

    If you like to write CoffeeScript you could do:

    hello = "foo"
    my_string = "I pity the #{hello}"
    

    CoffeeScript actually IS javascript, but with a much better syntax.

    For an overview of CoffeeScript check this beginner's guide.

    0 讨论(0)
  • 2020-11-22 03:11

    I would use the back-tick ``.

    let name1 = 'Geoffrey';
    let msg1 = `Hello ${name1}`;
    console.log(msg1); // 'Hello Geoffrey'
    

    But if you don't know name1 when you create msg1.

    For exemple if msg1 came from an API.

    You can use :

    let name2 = 'Geoffrey';
    let msg2 = 'Hello ${name2}';
    console.log(msg2); // 'Hello ${name2}'
    
    const regexp = /\${([^{]+)}/g;
    let result = msg2.replace(regexp, function(ignore, key){
        return eval(key);
    });
    console.log(result); // 'Hello Geoffrey'
    

    It will replace ${name2} with his value.

    0 讨论(0)
  • 2020-11-22 03:17

    var hello = "foo";

    var my_string ="I pity the";
    

    console.log(my_string, hello)

    0 讨论(0)
  • 2020-11-22 03:18

    You can use this javascript function to do this sort of templating. No need to include an entire library.

    function createStringFromTemplate(template, variables) {
        return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
            return variables[varName];
        });
    }
    
    createStringFromTemplate(
        "I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
        {
            list_name : "this store",
            var1      : "FOO",
            var2      : "BAR",
            var3      : "BAZ"
        }
    );
    

    Output: "I would like to receive email updates from this store FOO BAR BAZ."

    Using a function as an argument to the String.replace() function was part of the ECMAScript v3 spec. See this SO answer for more details.

    0 讨论(0)
提交回复
热议问题