Simple StringBuilder class in JavaScript.


function StringBuilder(value) {
this.strings = [];
this.append(value);
}

StringBuilder.prototype.append = function(value) {
if (value) {
this.strings.push(value);
}
return this;
}

StringBuilder.prototype.clear = function() {
this.strings = [];
}

StringBuilder.prototype.toString = function() {
return this.strings.join("");
}

Example:


var sb = new StringBuilder();

sb.append('This is a String ');
sb.append('That goes inside the ').append('String Builder.');

sb.toString();
sb.clear();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s