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

the*_*gah 8 javascript ruby

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

x = "sake"
puts "I like #{x}"
$"I like sake"
Run Code Online (Sandbox Code Playgroud)

例如:

def what_i_like(word)
  "I like #{word}"
end 
Run Code Online (Sandbox Code Playgroud)

在javascript中有类似的方法吗?

我现在正在做的是:

x = "sake"
"I like" + x + ". "
Run Code Online (Sandbox Code Playgroud)

小智 0

console.log 函数中的普通 Javascript 支持此功能。该格式的工作原理如下:

console.log('Hey %s', 'cat');
Run Code Online (Sandbox Code Playgroud)

这导致

"Hey cat"

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

%s = 字符串

%d = 整数或浮点数

%j = 可字符串化对象

在我看来,如果您已经以某种方式使用 Node.js,那么这种方法可能比使用模拟 ruby​​ 或 C 语法的外部库更惯用 javascript。

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