a simple StringBuilder class that pushes individual strings into an array and then uses the join method to produce the concatenated output string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Initializes a new instance of the StringBuilder class and appends the given value if supplied | |
function StringBuilder(value) | |
{ | |
this.strings = new Array(""); | |
this.append(value); | |
} | |
// Appends the given value to the end of this instance. | |
StringBuilder.prototype.append = function (value) | |
{ | |
if (value) | |
{ | |
this.strings.push(value); | |
} | |
} | |
// Clears the string buffer | |
StringBuilder.prototype.clear = function () | |
{ | |
this.strings.length = 1; | |
} | |
// Converts this instance to a String. | |
StringBuilder.prototype.toString = function () | |
{ | |
return this.strings.join(""); | |
} | |
//The code is so simple and straightforward that it should be self-explanatory. Now here's an example of how to use it: | |
// create a StringBuilder | |
var sb = new StringBuilder(); | |
// append some text | |
sb.append("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, "); | |
sb.append("sed diem nonummy nibh euismod tincidunt ut lacreet dolore "); | |
sb.append("magna aliguam erat volutpat."); | |
// get the full string value | |
var s = sb.toString(); |