繁体   English   中英

用字符串替换变量,例如console.log

[英]Substitute variables in strings like console.log

我想用console.log这样的字符串替换变量。 我想要实现的是这样的:

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对象。 像这样:

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):

function replaceStr(string, ...placeholders) {
    while (placeholders.length > 0) {
         string = string.replace('%s', placeholders.shift());
    }

    return string;
}

编辑:基于lexith的答案,我们可以避免显式循环:

function replaceStr(string, ...placeholders) {
    var count = 0;
    return string.replace(/%s/g, () => placeholders[count++]);
}

如果希望,您希望拥有自定义记录器功能。
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);
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM