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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4435149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:25:40  来源:igfitidea点击:

How can I insert a variable in a string in .js, coming from a ruby example

javascriptruby

提问by thenengah

In ruby you can insert variables into a string like this:

在 ruby​​ 中,您可以像这样将变量插入到字符串中:

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

For example:

例如:

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

Is there a similar way to do this in javascript?

在javascript中是否有类似的方法来做到这一点?

What I'm doing now is this:

我现在正在做的是:

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

采纳答案by zsalzbank

回答by Alex Webb

This feature is supported in vanilla Javascript in the console.log function. The format would work as follows:

此功能在 console.log 函数中的 vanilla Javascript 中受支持。格式如下:

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

which results in

这导致

"Hey cat"

"Hey cat"

If you happen to be using Node.js, this functionality is supported out of box with the util.format(...) function, working pretty much the same way except that it just returns a string.

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

%s = string

%s = 字符串

%d = integer or float

%d = 整数或浮点数

%j = stringifyable object

%j = 可字符串化的对象

Imo this approach might be slightly more idiomatic javascript than using an external library that simulates a ruby or C syntax, IF you are already using Node.js in some capacity.

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

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

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