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中做到这一点?
当前回答
跑龙套。格式可以做到这一点。
它将是v0.5.3的一部分,可以像这样使用:
var uri = util.format('http%s://%s%s',
(useSSL?'s':''), apiBase, path||'/');
其他回答
var user = "your name";
var s = 'hello ' + user + ', how are you doing';
在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
你需要在'(反撇号)而不是'(撇号)内换行字符串
我写了一个函数来精确地解决这个问题。
第一个参数是要参数化的字符串。你应该把你的变量放在这个字符串中,就像这样“%s1, %s2,…”% s12”。
其他参数分别是该字符串的参数。
/***
* @example parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
* @return "my name is John and surname is Doe"
*
* @firstArgument {String} like "my name is %s1 and surname is %s2"
* @otherArguments {String | Number}
* @returns {String}
*/
const parameterizedString = (...args) => {
const str = args[0];
const params = args.filter((arg, index) => index !== 0);
if (!str) return "";
return str.replace(/%s[0-9]+/g, matchedStr => {
const variableIndex = matchedStr.replace("%s", "") - 1;
return params[variableIndex];
});
}
例子
parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
// returns "my name is John and surname is Doe"
parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood");
// returns "this method sooo goood"
如果变量位置在字符串中改变了,这个函数也支持它而不改变函数参数。
parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
// returns "i have 5 books and 6 pencils."
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(格式化)