How can I do string interpolation in JavaScript?

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

提交回复
热议问题