JScript实现的一个String.Format方法

    在.NET Framework的BCL类String中,有一个很有用的静态方法 String.Format。当我们在输出一个需要由多个变量条目来组成的字符串时,非常的有用。特别是在对多语言支持时,使用Format方法来显示更加有价值。为了方便脚本编程,下面实现了一个JScript版的Format方法。

    BCL中的String.Format()是一个变参数的方法,第一个参数为格式化字符串,从第二个参数开始为格式化条目中的替换值。由于JavaScript天生就支持任意参数个数,所以可以很自然的实现一个非常sexy的Format方法。

    StringHelper.Format()方法源代码如下:
  //  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, '}');
 }

    开始的时候我使用Regular Expression来替换,结果发现问题巨多,多到我只能放弃了,老老实实的遍历替换。如果要保留"{"或"}",使用double来转义,和BCL类库String.Format用法完全一致。

    使用如下测试代码:
  alert(StringHelper.Format('{ 0 }{ 0 }, {{ 2 }}, {{ 1 }}', 'abc', 'def', 'ghi')); 

  alert(StringHelper.Format('{
0 }, {{ 2 }}, { 1 }', 'abc', 'def', 'ghi')); 

  alert(StringHelper.Format('{{
0 }}\r\n, { 2 }\r\n, { 1 }', 'abc', 'def', 'ghi')); 

  alert(StringHelper.Format('{
0 }{0}{{ 00 }{ 0 }, {{ 1 }}, {{ 2 }}', 'abc', 'def'));

    结果为:
 No.1 alert: abcabc, { 2 }, { 1 }

 No.2 alert: abc, {
2 }, def

 No.3 alert: {
0 }
                , ghi
                , def

 No.4 alert: abcabc{
00 }abc, { 1 }, { 2 }

    您还有更好更高效的实现办法吗?

你可能感兴趣的:(string.Format)