Some hours ago I published article about String.format. After it I made some improvements. And it's 3 types of this function. I think that first most useful becouse weight of code not importent , fastest version show speed only on arrays with 10000 elements.
Simpliest
String.prototype.format = function(values){
var str = this,i;
for(i in values)str = str.replace('%'+i,values[i])
return str;
}
//Using
'Hello, %0!'.format(['World'])
'Hello, %name!'.format({name:'World'})
Shortest
function format(str,values){
for(var i in values)str = str.replace('%'+i,values[i])
return str;
}
//Using
format('Hello, %0!',['World'])
format('Hello, %name!',{name:'World'})
Fastest (only list)
function format(str,values){
var i = values.length;
while(i--)str = str.replace('%'+i,values[i])
return str;
}
//Using
format('Hello, %0!',['World'])
format('Hello, %name!',{name:'World'}) //Not possible
What about when you want % in the string?
ОтветитьУдалитьNevermind, i misread. But what about when you have both %foo, and %foobar, sometimes the shorter will overwrite the longer?
ОтветитьУдалитьfunction format(str,values){
ОтветитьУдалитьfor(var i in values) {
str = str.replace(new RegExp('%'+i+'\\W', 'g'), values[i]);
}
return str;
}
this will fix the issue that id mentioned.
However, why not use a format that has a variable delimiter like "I like to {verb}" ? This will allow you to easily and accurately append strings to replacement variables e.g. "I like {animal}s" where "I like %animals" is ambiguous since it could be either `%animal` or `%animals`
wow this is epic, haven't seen something like this that can emulat printf like functions in C
ОтветитьУдалитьIt will probably break if you substitute %1 in at the first place. Something like:
ОтветитьУдалить"hello %0 world %1 whale".format(["%1", "something"]);
@kyle There is actually an sprintf package available for javascript https://github.com/wdavidw/node-printf
ОтветитьУдалитьAnother epic kluge from the epic kluge programming language - Javascript. I personally wish Javascript would crawl away into a corner and die.
ОтветитьУдалитьString.prototype.format = function()
ОтветитьУдалить{
var args = arguments;
return this.replace(/\{\d+\}/g, function(capture){ return args[capture.match(/\d+/)]; });
}
use:
'Hello, {0}!'.format( 'world');