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

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


当前回答

下面是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
>

其他回答

这样做:

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';
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"}) )

扩展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, console.log()将format string作为第一个参数:

 console.log('count: %d', count);