I have a string with say: My Name is %NAME% and my age is %AGE%.
%XXX%
are placeholders. We need to substitute values there from an object.
I have written a code that lets you format string easily.
function format() {
if (arguments.length === 0) {
throw "No arguments";
}
const string = arguments[0];
const lst = string.split("{}");
if (lst.length !== arguments.length) {
throw "Placeholder format mismatched";
}
let string2 = "";
let off = 1;
for (let i = 0; i < lst.length; i++) {
if (off < arguments.length) {
string2 += lst[i] + arguments[off++]
} else {
string2 += lst[i]
}
}
return string2;
}
format('My Name is {} and my age is {}', 'Mike', 26);
My Name is Mike and my age is 26