Well , in python or java or ... we do sth like : (the python version )
tmp = "how%s" %("isit")
and now tmp looks like "howisit".
is there any bulit in thing like that in javascript ? ( rather than sprintf )
Thanks
Well , in python or java or ... we do sth like : (the python version )
tmp = "how%s" %("isit")
and now tmp looks like "howisit".
is there any bulit in thing like that in javascript ? ( rather than sprintf )
Thanks
Not build in, but you can make your own templating by extending the String prototype:
String.prototype.template = String.prototype.template ||
function(){
var args = arguments;
function replacer(a){
return args[Number(a.slice(1))-1] || a;
}
return this.replace(/(\$)?\d+/gm,replacer)
};
// usages
'How$1'.template('isit'); //=> Howisit
var greet = new Date('2012/08/08 08:00') < new Date
? ['where','yesterday'] : ['are','today'];
'How $1 you $2?'.template(greet[0],greet[1]); // How where you yesterday?
No builtin function is there, however you can very easily build one yourself. The replace function can take a function argument and is the perfect solution for this work. Although be careful with large strings and complicated expressions as this might get slow quickly.
var formatString = function(str) {
// get all the arguments after the first
var replaceWith = Array.prototype.slice.call(arguments, 1);
// simple replacer based on String, Number
str.replace(/%\w/g, function() {
return replaceWith.shift();
});
};
var newString = formatString("how %s %s?", "is", "it");
I think you can use these (simplistic) snippets;
function formatString(s, v) {
var s = (''+ s), ms = s.match(/(%s)/g), m, i = 0;
if (!ms) return s;
while(m = ms.shift()) {
s = s.replace(/(%s)/, v[i]);
i++;
}
return s;
}
var s = formatString("How%s", ["isit"]);
Or;
String.prototype.format = function() {
var s = (""+ this), ms = s.match(/(%s)/g) || [], m, v = arguments, i = 0;
while(m = ms.shift()) {
s = s.replace(/(%s)/, v[i++]);
}
return s;
}
var s = "id:%s, name:%s".format(1,"Kerem");
console.log(s);