One of the things I like in .NET is the StringBuilder class and since like .NET, JavaScript strings are immutable it makes sense to have one for JavaScript too. I’ve wrote a simple approximation that uses Array and Array.join().

I’ve built this version for use with Ext however you can easily adapt it to run outside of Ext:

Ext.namespace("Ext.util");

Ext.util.StringBuilder = function()
{

    var buffer = [];
    var length = 0;

    this.getLength = function()
    {
        return length;
    };

    this.clear = function()
    {
        buffer = [];
        length = 0;
    };

    this.append = function(s)
    {
        if (s == null) return;

        length += s.length;
        buffer.push(s);
    };

    this.appendLine = function(s)
    {
        if (s == null) return;

        var _s = s + "\r\n";

        length += _s.length;
        buffer.push(_s);
    };

    this.toString = function()
    {
        return buffer.join("");
    };

}

You can use it like this:

var sb = new Ext.util.StringBuilder();

sb.append("Hello");
sb.append(" ");
sb.append("World");

var s = sb.toString();

alert(s);

Leave a Comment