如何将变量放在javascript字符串中? (Node.js) [英] How do I put variables inside javascript strings? (Node.js)
本文介绍了如何将变量放在javascript字符串中? (Node.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
推荐答案
如果您想要类似的东西,可以创建一个函数:
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字符串中? (Node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文