如何在.js中的字符串中插入变量,来自ruby示例

在ruby中,您可以将变量插入到字符串中,如下所示:

x = "sake" puts "I like #{x}" $"I like sake" 

例如:

 def what_i_like(word) "I like #{word}" end 

在javascript中有类似的方法吗?

我现在正在做的是:

 x = "sake" "I like" + x + ". " 

看看这篇文章: 相当于printf / string.format的JavaScript

console.log函数中的vanilla Javascript支持此function。 格式如下:

 console.log('Hey %s', 'cat'); 

结果

"Hey cat"

如果您碰巧使用Node.js,则使用util.format(…)函数支持此function,其工作方式几乎相同,只是它只返回一个字符串。

%s =字符串

%d =整数或浮点数

%j = stringifyable对象

Imo这种方法可能比使用模拟ruby或C语法的外部库稍微更惯用javascript,如果您已经在某种程度上使用Node.js。

https://nodejs.org/api/util.html#util_util_format_format