How can I do string interpolation in JavaScript?

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

    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.

提交回复
热议问题