Today, I wrote a stringbuilder class similar to the stringbuilder class in C # In JavaScript, which can be called in Javascript. This class is used to process a large number of String concatenation, so thatCodeEasy to read and maintain.
First introduce stringbuilder. js
< Script Type = "Text/JavaScript" SRC = "Stringbuilder. js" > </ Script >
Then you can easily use it:
Basic usage:
VaR Sb = New Stringbuilder ();
SB. append ( " Hello " );
SB. append ( " World! " );
VaR Result = SB. tostring ();
Usage 2:
Code
// SB. appendformat ("{0}... {n}", "A",... "N ");
VaR Sb2 = New Stringbuilder ();
VaR A = " Xi Hu " ;
VaR B = 21 ;
VaR C = " Male " ;
Sb2.append ( " Welcome! " );
Sb2.appendformat ( " My name is {0}, age: {1}, Gender: {2} " , A, B, C );
Usage 3:
Code
// SB. appendformat ("{0}... {n}", array );
VaR Sb3 = New Stringbuilder ();
// One-to-one correspondence with Arrays
VaR Param = New Array ();
Param [ 0 ] = " 20 " ;
Param [ 1 ] = " Breeze level 3 " ;
Param [ 2 ] = " Southeast wind " ;
Param [ 3 ] = " Sunny " ;
Param [ 4 ] = New Date (). tolocaledatestring ();
Sb3.appendformat ( " Today: {4}, temperature: {0}, wind: {1}, wind direction: {2}, {3} " , Param );
Complete sample code:
Code
< Html >
< Head >
< Title > Javascript stringbuilder demo </ Title >
< Script Type = "Text/JavaScript" SRC = "Stringbuilder. js" > </ Script >
< Script Type = "Text/JavaScript" >
// Created by hooyes
// Basic usage
VaR Sb = New Stringbuilder ();
SB. append ( " Hello " );
SB. append ( " World! " );
VaR Result = SB. tostring ();
Document. Write (result );
Document. Write ( " <HR/> " );
// Usage 2
// SB. appendformat ("{0}... {n}", "A",... "N ");
VaR Sb2 = New Stringbuilder ();
VaR A = " Xi Hu " ;
VaR B = 21 ;
VaR C = " Male " ;
Sb2.append ( " Welcome! " );
Sb2.appendformat ( " My name is {0}, age: {1}, Gender: {2} " , A, B, C );
Document. Write (sb2.tostring ());
Document. Write ( " <HR/> " );
// Usage 3
// SB. appendformat ("{0}... {n}", array );
VaR Sb3 = New Stringbuilder ();
// One-to-one correspondence with Arrays
VaR Param = New Array ();
Param [ 0 ] = " 20 " ;
Param [ 1 ] = " Breeze level 3 " ;
Param [ 2 ] = " Southeast wind " ;
Param [ 3 ] = " Sunny " ;
Param [ 4 ] = New Date (). tolocaledatestring ();
Sb3.appendformat ( " Today: {4}, temperature: {0}, wind: {1}, wind direction: {2}, {3} " , Param );
Document. Write (sb3.tostring ());
</ Script >
</ Head >
< Body >
</ Body >
</ Html >
Download stringbuilder. js code and example:
/Files/hooyes/jsstringbuilder.rar