代码之家  ›  专栏  ›  技术社区  ›  Anonymous Group

替换字符串中的变量,如console.log

  •  2
  • Anonymous Group  · 技术社区  · 8 年前

    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.
    */
    

    我不知道该怎么做。任何帮助都将不胜感激。

    非常感谢。

    3 回复  |  直到 8 年前
        1
  •  3
  •   malifa    8 年前

    您可以将其原型化为 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'
    
        2
  •  2
  •   Alberto Trindade Tavares    8 年前

    您可以使用扩展运算符(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++]);
    }
    
        3
  •  0
  •   Ajay    8 年前

    如果希望你想有自定义记录器功能。
    console.log 可以替换 %s ,使用下面的方法,您的自定义函数将获得控制台的完整功能集。日志及其更高效。

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