最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Substitute variables in strings like console.log - Stack Overflow

programmeradmin1浏览0评论

I want to substitute variables in a string like console.log does. What I want to achieve is something like this:

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

I am not able to figure out how to do that. Any help will be much appreciated.

Thank you.

I want to substitute variables in a string like console.log does. What I want to achieve is something like this:

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

I am not able to figure out how to do that. Any help will be much appreciated.

Thank you.

Share Improve this question asked Jun 28, 2017 at 13:23 Anonymous GroupAnonymous Group 651 silver badge5 bronze badges 3
  • 1 Is there any reason you aren't using template literals? – Christopher Moore Commented Jun 28, 2017 at 13:38
  • 1 @ChristopherMoore What I want to achieve is not what template literals offer. – Anonymous Group Commented Jun 28, 2017 at 13:45
  • It's quite sad that console does not offer separate method to format string output. Template literals expect that the substitutions are immediately available, which is not always the case. The syntax also is different, which is unhandy for custom logger. – Dmitriy Sintsov Commented Dec 16, 2024 at 8:14
Add a ment  | 

4 Answers 4

Reset to default 3

You could prototype it to the String object. Something like this:

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'

You can use spread operator (ES6):

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

    return string;
}

EDIT: Based on lexith's answer, we can avoid the explicit loop:

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

If hope you want to have custom logger function.
console.log can replace %s, with below approach your custom function gets full feature set of console.log and its more efficient.

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);
   }
}
function replaceStr(string, ...placeholders) {
    const replaced = string.replace(/%s/g, () => placeholders.shift());
    return [replaced, ...placeholders].join(' ');
}

This will append any remaining placeholders to the string to more accurately replicate console.log.

发布评论

评论列表(0)

  1. 暂无评论