Skip to content

Instantly share code, notes, and snippets.

@benjamin-wss
Last active August 28, 2019 16:44
Show Gist options
  • Save benjamin-wss/0a8a55673f2a5f21766c to your computer and use it in GitHub Desktop.
Save benjamin-wss/0a8a55673f2a5f21766c to your computer and use it in GitHub Desktop.
String builder for JavaScript
function StringBuilder(value) {
this.strings = new Array();
this.append(value);
}
StringBuilder.prototype.append = function (value) {
if (value) {
this.strings.push(value);
}
}
StringBuilder.prototype.clear = function () {
this.strings.length = 0;
}
StringBuilder.prototype.toString = function () {
return this.strings.join("");
}
var sb = new StringBuilder();
sb.append("This is");
sb.append("much better looking");
sb.append("than using +=");
// joins the string
var myString = sb.toString();
// Cleans out the string buffer in the StringBuilder.
// This effectively makes it empty in case you did not
// know what cleaning out a buffer in this context
// meant.
sb.clear();
@SenayYakut
Copy link

Can you please write more comments for the StringBuilder.js
I am trying to understand how it works.
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment