javascript NodeJS 字符串格式像 Python 一样吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10788408/
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-26 11:01:46  来源:igfitidea点击:

NodeJS String format like Python?

javascriptpythonnode.jsv8

提问by Alex Ivasyuv

In python, I can do the following:

在 python 中,我可以执行以下操作:

name = "bob"

print("Hey, %s!" % name)

Is there anything similar to that (or Python's .format()) in JavaScript/NodeJS?

.format()JavaScript/NodeJS 中是否有类似于(或 Python 的)的东西?

采纳答案by Jakob Bowyer

sprintfshould do what you are asking for I think.

sprintf应该做你所要求的我认为。

回答by Alex Ivasyuv

You can use util.format, it's printflike function.

您可以使用util.formatprintf就像函数一样。

回答by nickool

Another option is template strings

另一种选择是模板字符串

For example:

例如:

const name = "bob";
console.log(`Hey, ${name}!`);