Skip to content
Advertisement

Substitute variables in strings like console.log

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.

Advertisement

Answer

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'
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement