Javascript 替换字符串中的变量,如console.log
我想替换字符串中的变量,比如Javascript 替换字符串中的变量,如console.log,javascript,node.js,string,replace,console.log,Javascript,Node.js,String,Replace,Console.log,我想替换字符串中的变量,比如console.logdoes。 我想要实现的是这样的目标: let str = 'My %s is %s.'; replaceStr(string, /* args */) { // I need help with defining this function }; let newStr = replaceStr(str, 'name', 'Jackie'); console.log(newStr); // output => My name i
console.log
does。
我想要实现的是这样的目标:
let str = 'My %s is %s.';
replaceStr(string, /* args */) {
// I need help with defining this function
};
let newStr = replaceStr(str, 'name', 'Jackie');
console.log(newStr);
// output => My name is Jackie.
/*
This is similar to how console.log does:
// console.log('I\'m %s.', 'Jack');
// => I'm Jack.
*/
String.prototype.sprintf = function() {
var counter = 0;
var args = arguments;
return this.replace(/%s/g, function() {
return args[counter++];
});
};
let str = 'My %s is %s.';
str = str.sprintf('name', 'Alex');
console.log(str); // 'My name is Alex'
我不知道该怎么做。任何帮助都将不胜感激
谢谢。您可以使用扩展运算符(ES6): 编辑:根据lexith的回答,我们可以避免显式循环:
function replaceStr(string, ...placeholders) {
var count = 0;
return string.replace(/%s/g, () => placeholders[count++]);
}
您可以将其原型化为
字符串
对象。大概是这样的:
let str = 'My %s is %s.';
replaceStr(string, /* args */) {
// I need help with defining this function
};
let newStr = replaceStr(str, 'name', 'Jackie');
console.log(newStr);
// output => My name is Jackie.
/*
This is similar to how console.log does:
// console.log('I\'m %s.', 'Jack');
// => I'm Jack.
*/
String.prototype.sprintf = function() {
var counter = 0;
var args = arguments;
return this.replace(/%s/g, function() {
return args[counter++];
});
};
let str = 'My %s is %s.';
str = str.sprintf('name', 'Alex');
console.log(str); // 'My name is Alex'
如果希望您拥有自定义记录器功能。
console.log
可以取代%s
,通过下面的方法,您的自定义函数可以获得console.log的完整功能集及其更高效的功能
function myLogger() {
if(logEnabled) {
// you can play with arguments for any customisation's
// arguments[0] is first string
// prepend date in log arguments[0] = (new Date().toString()) + arguments[0] ;
console.log.apply(console, arguments);
}
}
我正在考虑这个问题,但我希望找到一种不使用循环的方法。这可能吗?请参阅lexith对
控制台
可以做的远不止%s
:有什么原因你不使用吗?@christophemore我想要实现的不是模板文本提供的。