In the. NET Framework's Bcl class string, there is a useful static method string. format. It is useful when outputting a string consisting of multiple variable entries. Especially when supporting multiple languages, it is more valuable to use the format method. To facilitate Script Programming, A JScript format method is implemented below.
String. Format () in BCl is a variable parameter method. The first parameter is a formatted string, and the second parameter is the replacement value in the formatting entry. Because JavaScript supports the number of arbitrary parameters, it is natural to implement a very sexy format method.
Stringhelper. Format () methodSource codeAs follows:
// 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 ,'}');
}
At the beginning, I used the regular expression to replace it. As a result, I found a lot of problems. Many times I had to give up, and I honestly replaced the traversal. If you want to retain "{" or "}", use double to escape. This is exactly the same as the usage of string. format in the Bcl class library.
Use the following testCode:
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 '));
Result:
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 }
Do you have a better and more efficient implementation method?