How can I do string interpolation in JavaScript?

前端 未结 19 2531
慢半拍i
慢半拍i 2020-11-21 07:54

Consider this code:

var age = 3;

console.log(\"I\'m \" + age + \" years old!\");

Are there any other ways to insert the value of a variabl

相关标签:
19条回答
  • 2020-11-21 08:01

    Douglas Crockford's Remedial JavaScript includes a String.prototype.supplant function. It is short, familiar, and easy to use:

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

    If you don't want to change String's prototype, you can always adapt it to be standalone, or place it into some other namespace, or whatever.

    0 讨论(0)
  • 2020-11-21 08:02

    Word of caution: avoid any template system which does't allow you to escape its own delimiters. For example, There would be no way to output the following using the supplant() method mentioned here.

    "I am 3 years old thanks to my {age} variable."

    Simple interpolation may work for small self-contained scripts, but often comes with this design flaw that will limit any serious use. I honestly prefer DOM templates, such as:

    <div> I am <span id="age"></span> years old!</div>
    

    And use jQuery manipulation: $('#age').text(3)

    Alternately, if you are simply just tired of string concatenation, there's always alternate syntax:

    var age = 3;
    var str = ["I'm only", age, "years old"].join(" ");
    
    0 讨论(0)
  • 2020-11-21 08:02

    Try kiwi, a light-weight JavaScript module for string interpolation.

    You can do

    Kiwi.compose("I'm % years old!", [age]);
    

    or

    Kiwi.compose("I'm %{age} years old!", {"age" : age});
    
    0 讨论(0)
  • 2020-11-21 08:11

    I use this pattern in a lot of languages when I don't know how to do it properly yet and just want to get an idea down quickly:

    // JavaScript
    let stringValue = 'Hello, my name is {name}. You {action} my {relation}.'
        .replace(/{name}/g    ,'Indigo Montoya')
        .replace(/{action}/g  ,'killed')
        .replace(/{relation}/g,'father')
        ;
    

    While not particularily efficient, I find it readable. It always works, and its always available:

    ' VBScript
    dim template = "Hello, my name is {name}. You {action} my {relation}."
    dim stringvalue = template
    stringValue = replace(stringvalue, "{name}"    ,"Luke Skywalker")     
    stringValue = replace(stringvalue, "{relation}","Father")     
    stringValue = replace(stringvalue, "{action}"  ,"are")
    

    ALWAYS

    * COBOL
    INSPECT stringvalue REPLACING FIRST '{name}'     BY 'Grendel'
    INSPECT stringvalue REPLACING FIRST '{relation}' BY 'Mother'
    INSPECT stringvalue REPLACING FIRST '{action}'   BY 'did unspeakable things to'
    
    0 讨论(0)
  • 2020-11-21 08:11

    Couldn't find what I was looking for, then found it -

    If you're using Node.js, there's a built-in utilpackage with a format function that works like this:

    util.format("Hello my name is %s", "Brent");
    > Hello my name is Brent
    

    Coincidentally this is now built into console.log flavors too in Node.js -

    console.log("This really bad error happened: %s", "ReferenceError");
    > This really bad error happened: ReferenceError
    
    0 讨论(0)
  • 2020-11-21 08:14

    You could use Prototype's template system if you really feel like using a sledgehammer to crack a nut:

    var template = new Template("I'm #{age} years old!");
    alert(template.evaluate({age: 21}));
    
    0 讨论(0)
提交回复
热议问题