javascript - javaScript有什么语句等同于printf/string.format

我正在寻找一个等效于c/php printf()或C#/Java程序员String.Format() (IFormatProvider 的JavaScript函数)。

我知道微软的ajax库提供了String.Format()版本,但是我不希望用这么大的框架,整个开销太大了。

时间:

试用sprintf ()用于JavaScript



"{0}{1}".format("{1}","{0}")


// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
 String.prototype.format = function() {
 var args = arguments;
 return this.replace(/{(d+)}/g, function(match, number) { 
 return typeof args[number] != 'undefined'
 ? args[number]
 : match
 ;
 });
 };
}

"{0} is dead, but {1} is alive! {0} {2}".format("ASP","ASP.NET")

输出

ASP is dead ,but ASP.NET is alive! ASP {2}


如果你不希望修改String的Prototype,请执行以下操作:


if (!String.format) {
 String.format = function(format) {
 var args = Array.prototype.slice.call(arguments, 1);
 return format.replace(/{(d+)}/g, function(match, number) { 
 return typeof args[number] != 'undefined'
 ? args[number] 
 : match
 ;
 });
 };
}

String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');

相同的结果:

ASP is dead ,but ASP.NET is alive! ASP {2}

jsxt,zippo


String.prototype.format = function() {
 var formatted = this;
 for (var i = 0; i < arguments.length; i++) {
 var regexp = new RegExp('{'+i+'}', 'gi');
 formatted = formatted.replace(regexp, arguments[i]);
 }
 return formatted;
};

使用这个方法,可以替换如下字符串:


'The {0} is dead. Don't code {0}. Code {1} that is open source!'.format('ASP', 'PHP');

Firebug

Hello, Gabriel, are you feeling OK?

可以将对象,数组和字符串用作参数!


if (!String.prototype.format) {
 String.prototype.format = function() {
 var str = this.toString();
 if (!arguments.length)
 return str;
 var args = typeof arguments[0],
 args = (("string" == args ||"number" == args) ? arguments : arguments[0]);
 for (arg in args)
 str = str.replace(RegExp("{" + arg +"}","gi"), args[arg]);
 return str;
 }
}

我使用这个简单的函数:


String.prototype.format = function() {
 var formatted = this;
 for( var arg in arguments ) {
 formatted = formatted.replace("{" + arg +"}", arguments[arg]);
 }
 return formatted;
};

这与string.format非常相似:


"{0} is dead, but {1} is alive!".format("ASP","ASP.NET")

下面是在JavaScript中对sprintf的最小实现:


function sprintf() {
 var args = arguments,
 string = args[0],
 i = 1;
 return string.replace(/%((%)|s|d)/g, function (m) {
 // m is the matched format, e.g. %s, %d
 var val = null;
 if (m[2]) {
 val = m[2];
 } else {
 val = args[i];
 // A switch statement so that the formatter can be extended. Default is %s
 switch (m) {
 case '%d':
 val = parseFloat(val);
 if (isNaN(val)) {
 val = 0;
 }
 break;
 }
 i++;
 }
 return val;
 });
}

例如:


alert(sprintf('Latitude: %s, Longitude: %s, Count: %d', 41.847, -87.661, 'two'));
// Expected output: Latitude: 41.847, Longitude: -87.661, Count: 0


String.prototype.format = function() {
 var formatted = this;
 for (var arg in arguments) {
 formatted = formatted.replace("{" + arg +"}", arguments[arg]);
 }
 return formatted;
};

我将添加我自己发现的我发现的发现:

遗憾的是,sprintf似乎没有处理千位分隔符格式,比如. NET's 字符串格式。

...