Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 269
Anonymous Group Avatar asked Nov 27 '25 23:11

Anonymous Group


2 Answers

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'
like image 51
malifa Avatar answered Nov 29 '25 12:11

malifa


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++]);
}
like image 44
Alberto Trindade Tavares Avatar answered Nov 29 '25 13:11

Alberto Trindade Tavares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!