How can I do string interpolation in JavaScript?

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

    I am years old!

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

提交回复
热议问题