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中做到这一点?
当前回答
注意,从2015年开始,模板只使用反引号
https://stackoverflow.com/a/37245773/294884
let a = `hello ${name}` // NOTE!!!!!!!! ` not ' or "
注意,这是一个反引号,而不是引号。
如果你想要类似的东西,你可以创建一个函数:
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的转义。但我希望这能给你们一些启发。我很确定也有库提供了类似的功能。
其他回答
扩展String的几种方法。原型,或使用ES2015模板文字。
var result = document.querySelector('#result'); // ----------------------------------------------------------------------------------- // Classic String.prototype.format = String.prototype.format || function () { var args = Array.prototype.slice.call(arguments); var replacer = function (a){return args[a.substr(1)-1];}; return this.replace(/(\$\d+)/gm, replacer) }; result.textContent = 'hello $1, $2'.format('[world]', '[how are you?]'); // ES2015#1 'use strict' String.prototype.format2 = String.prototype.format2 || function(...merge) { return this.replace(/\$\d+/g, r => merge[r.slice(1)-1]); }; result.textContent += '\nHi there $1, $2'.format2('[sir]', '[I\'m fine, thnx]'); // ES2015#2: template literal var merge = ['[good]', '[know]']; result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`; <pre id="result"></pre>
从node.js >4.0开始,它与ES6标准更加兼容,其中字符串操作得到了极大的改进。
原始问题的答案可以很简单:
var s = `hello ${my_name}, how are you doing`;
// note: tilt ` instead of single quote '
字符串可以展开多行,这使得模板或HTML/XML处理非常容易。关于它的更多细节和功能:模板字面量是在mozilla.org上的字符串字面量。
如果使用node.js, console.log()将format string作为第一个参数:
console.log('count: %d', count);
这样做:
s = 'hello ' + my_name + ', how are you doing'
更新
使用ES6,你也可以这样做:
s = `hello ${my_name}, how are you doing`
如果你使用的是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