如何将变量放在javascript字符串中? [英] How do I put variables inside javascript strings?
问题描述
s = 'hello %s, how are you doing' % (my_name)
这就是您在python中执行此操作的方式.您如何在javascript/node.js中做到这一点?
That's how you do it in python. How can you do that in javascript/node.js?
推荐答案
请注意,从2015年开始,只需使用反引号进行模板制作
Note, from 2015 onwards, just use backticks for templating
https://stackoverflow.com/a/37245773/294884
let a = `hello ${name}` // NOTE!!!!!!!! ` not ' or "
请注意,这是一个反引号,而不是引号.
Note that it is a backtick, not a quote.
如果您想要类似的东西,可以创建一个函数:
If you want to have something similar, you could create a function:
function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;
return str.replace(/%s/g, () => args[i++]);
}
用法:
s = parse('hello %s, how are you doing', my_name);
这只是一个简单的示例,并未考虑不同类型的数据类型(例如%i
等)或%s
的转义.但我希望它能给您一些想法.我很确定那里也有提供这种功能的库.
This is only a simple example and does not take into account different kinds of data types (like %i
, etc) or escaping of %s
. But I hope it gives you some idea. I'm pretty sure there are also libraries out there which provide a function like this.
这篇关于如何将变量放在javascript字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!