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对=)的回答。@AnonymousGroup根据lexith的回答添加了一个解决方案,该解决方案避免了循环,并且由于ES6的功能(扩展运算符、箭头函数)而简洁。@Albertortindadetavares您尝试过吗?这不符合预期。:/Lexith的答案似乎是正确的。我试过了,但它在支持ES6的浏览器中运行。Lexith的答案是控制台可以做的远不止
%s
:有什么原因你不使用吗?@christophemore我想要实现的不是模板文本提供的。