How can I do string interpolation in JavaScript?

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

    While templates are probably best for the case you describe, if you have or want your data and/or arguments in iterable/array form, you can use String.raw.

    String.raw({
      raw: ["I'm ", " years old!"]
    }, 3);
    

    With the data as an array, one can use the spread operator:

    const args = [3, 'yesterday'];
    String.raw({
      raw: ["I'm ", " years old as of ", ""]
    }, ...args);
    

提交回复
热议问题