您的位置:首页 > Web前端 > JavaScript

JScript实现的一个String.Format方法-转载

2010-06-10 09:37 651 查看
本文转载自作者:鸟食轩

// StringHelper.Format('{0}, {2}, {1}', 'abc', 'def', 'ghi');
// return "abc, ghi, def".
StringHelper.Format = function(format)
{
if ( arguments.length == 0 )
{
return '';
}
if ( arguments.length == 1 )
{
return String(format);
}

var strOutput = '';
for ( var i=0 ; i < format.length-2 ; )
{
if ( format.charAt(i) == '{' && format.charAt(i+1) != '{' )
{
var token = format.substr(i);
var index = String(token.match(/\d+/));
if ( format.charAt(i+index.length+1) == '}' )
{
var swapArg = arguments[Number(index)+1];
if ( swapArg )
{
strOutput += swapArg;
}
i += index.length+2;
}
}
else
{
if ( format.charAt(i) == '{' && format.charAt(i+1) == '{' )
{
strOutput += format.charAt(i);
i++
}
strOutput += format.charAt(i);
i++;
}
}
strOutput += format.substr(i);
return strOutput.replace(/{{/g, '{').replace(/}}/g, '}');
}

www.paipai1688.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐