s = 'hello %s, how are you doing' % (my_name)

在python中就是这么做的。如何在javascript/node.js中做到这一点?


当前回答

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(格式化)

其他回答

这样做:

s = 'hello ' + my_name + ', how are you doing'

更新

使用ES6,你也可以这样做:

s = `hello ${my_name}, how are you doing`
var user = "your name";
var s = 'hello ' + user + ', 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

var print = console.log;

function dformat(str, ...arr) {
  return str.replace(/%(\d+)/g, function(_,i) {
    return arr[--i];
  });
}

function wformat(str, dict) {
  return str.replace(/%(\w+)/g, function(_,k) {
    return dict[k];
  });
}

function sformat(str, dict) {
  return str.replace(/\$(\w+)/g, function(_,m) {
    return dict[m];
  });
}

function tformat(str, dict) {
  return str.replace(/\${(\w+)}/g, function(_,m) {
    return dict[m];
  });
}

print(1, dformat("uid:%1, name:%2", 120, "someone") )
print(2, wformat("color: %name", {name: "green"})   )
print(3, sformat("img: $url", {url: "#"})   )
print(4, tformat("${left} ${right}", {right:"1000", left: "7fff"}) )

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(格式化)