How can I do string interpolation in JavaScript?

前端 未结 19 2534
慢半拍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:20

    Try sprintf library (a complete open source JavaScript sprintf implementation). For example:

    vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
    

    vsprintf takes an array of arguments and returns a formatted string.

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

    Here's a solution which requires you to provide an object with the values. If you don't provide an object as parameter, it will default to using global variables. But better stick to using the parameter, it's much cleaner.

    String.prototype.interpolate = function(props) {
        return this.replace(/\{(\w+)\}/g, function(match, expr) {
            return (props || window)[expr];
        });
    };
    
    // Test:
    
    // Using the parameter (advised approach)
    document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 });
    
    // Using the global scope
    var eruption2 = 116;
    document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate();
    <div id="resultA"></div><div id="resultB"></div>

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

    Using template syntax fails in older browsers, important if you are creating HTML for public use. Using concatenation is tedious and hard to read, particularly if you have many or long expressions, or if you must use parentheses to handle mixtures of number and string items (both of which use the + operator).

    PHP expands quoted strings containing variables and even some expressions using a very compact notation: $a="the color is $color";

    In JavaScript, an efficient function can be written to support this: var a=S('the color is ',color);, using a variable number of arguments. While there is no advantage over concatenation in this example, when the expressions get longer this syntax may be clearer. Or one can use the dollar sign to signal the start of an expression using a JavaScript function, as in PHP.

    On the other hand, writing an efficient workaround function to provide template-like expansion of strings for older browsers wouldn't be hard. Someone has probably done it already.

    Finally, I imagine that sprintf (as in C, C++, and PHP) could be written in JavaScript, although it would be a little less efficient than these other solutions.

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

    Supplant more for ES6 version of @Chris Nielsen's post.

    String.prototype.supplant = function (o) {
      return this.replace(/\${([^\${}]*)}/g,
        (a, b) => {
          var r = o[b];
          return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
      );
    };
    
    string = "How now ${color} cow? {${greeting}}, ${greeting}, moo says the ${color} cow.";
    
    string.supplant({color: "brown", greeting: "moo"});
    => "How now brown cow? {moo}, moo, moo says the brown cow."
    
    0 讨论(0)
  • 2020-11-21 08:25

    You can do easily using ES6 template string and transpile to ES5 using any available transpilar like babel.

    const age = 3;
    
    console.log(`I'm ${age} years old!`);
    

    http://www.es6fiddle.net/im3c3euc/

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

    If you want to interpolate in console.log output, then just

    console.log("Eruption 1: %s", eruption1);
                             ^^
    

    Here, %s is what is called a "format specifier". console.log has this sort of interpolation support built-in.

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