How can I do string interpolation in JavaScript?

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

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

提交回复
热议问题