I want to substitute variables in a string like console.log
does.
What I want to achieve is something like this:
JavaScript
x
16
16
1
let str = 'My %s is %s.';
2
3
replaceStr(string, /* args */) {
4
// I need help with defining this function
5
};
6
7
let newStr = replaceStr(str, 'name', 'Jackie');
8
console.log(newStr);
9
// output => My name is Jackie.
10
11
/*
12
This is similar to how console.log does:
13
// console.log('I'm %s.', 'Jack');
14
// => I'm Jack.
15
*/
16
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:
JavaScript
1
13
13
1
String.prototype.sprintf = function() {
2
var counter = 0;
3
var args = arguments;
4
5
return this.replace(/%s/g, function() {
6
return args[counter++];
7
});
8
};
9
10
let str = 'My %s is %s.';
11
str = str.sprintf('name', 'Alex');
12
console.log(str); // 'My name is Alex'
13