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中做到这一点?
当前回答
试试JS中的sprintf 或者你可以用这个要点
其他回答
跑龙套。格式可以做到这一点。
它将是v0.5.3的一部分,可以像这样使用:
var uri = util.format('http%s://%s%s',
(useSSL?'s':''), apiBase, path||'/');
扩展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>
const格式=(…args) = > args.shift () .replace (/ % ([jsd]) / g, x = > x = = =“% j”?JSON.stringify(args.shift()): const name = 'Csaba' const格式化= format('Hi %s,今天是%s,您的数据是%j',名称,日期(),{数据:{国家:'匈牙利',城市:'布达佩斯'}}) console.log(格式化)
试试JS中的sprintf 或者你可以用这个要点
在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
你需要在'(反撇号)而不是'(撇号)内换行字符串