s = 'hello %s, how are you doing' % (my_name)
在python中就是这么做的。如何在javascript/node.js中做到这一点?
s = 'hello %s, how are you doing' % (my_name)
在python中就是这么做的。如何在javascript/node.js中做到这一点?
当前回答
在Node.js v4中,你可以使用ES6的Template字符串
var my_name = 'John';
var s = `hello ${my_name}, how are you doing`;
console.log(s); // prints hello John, how are you doing
你需要在'(反撇号)而不是'(撇号)内换行字符串
其他回答
这样做:
s = 'hello ' + my_name + ', how are you doing'
更新
使用ES6,你也可以这样做:
s = `hello ${my_name}, how are you doing`
从node.js >4.0开始,它与ES6标准更加兼容,其中字符串操作得到了极大的改进。
原始问题的答案可以很简单:
var s = `hello ${my_name}, how are you doing`;
// note: tilt ` instead of single quote '
字符串可以展开多行,这使得模板或HTML/XML处理非常容易。关于它的更多细节和功能:模板字面量是在mozilla.org上的字符串字面量。
var user = "your name";
var s = 'hello ' + user + ', how are you doing';
下面是Node.js中的一个多行字符串文本示例。
> let name = 'Fred'
> tm = `Dear ${name},
... This is to inform you, ${name}, that you are
... IN VIOLATION of Penal Code 64.302-4.
... Surrender yourself IMMEDIATELY!
... THIS MEANS YOU, ${name}!!!
...
... `
'Dear Fred,\nThis is to inform you, Fred, that you are\nIN VIOLATION of Penal Code 64.302-4.\nSurrender yourself IMMEDIATELY!\nTHIS MEANS YOU, Fred!!!\n\n'
console.log(tm)
Dear Fred,
This is to inform you, Fred, that you are
IN VIOLATION of Penal Code 64.302-4.
Surrender yourself IMMEDIATELY!
THIS MEANS YOU, Fred!!!
undefined
>
如果你使用的是ES6,你应该使用模板文字。
//you can do this
let sentence = `My name is ${ user.name }. Nice to meet you.`
点击此处阅读更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals