js 字符串拼接方法,类似c#的StringBuilder

之前写的一个字符串拼接的方法,类似C#中的StringBuilder方法,在这分享给大家:

$.StringBuffer=function(){
        this._strings_ = new Array();
        if (typeof $.StringBuffer._initialized == "undefined") {
            $.StringBuffer.prototype = {
                append:function(str){
                    if(typeof str == 'string'){
                        this._strings_.push(str);
                    }
                },
                appendFormat:function(str){
                    var args = arguments;
                    str = str.replace(/\{(\d+)\}/g, function(m, i){
                        return args[++i];
                    });
                    this._strings_.push(str);
                },
                toString:function(){
                    if(typeof arguments[0]=='string'){
                        return this._strings_.join(arguments[0]);
                    }
                    return this._strings_.join("");
                },
                clear:function(){
                    this._strings_ = [];
                }
            };
            $.StringBuffer._initialized = true;
        };
    };

实质还是用的数组的拼接方法,并加了replace方法进行格式化字符串,示例:

var str = new $.StringBuffer();
str.append("<ul class='aa'>");
str.appendFormat("<li><a href='{0}' title='{1}'>{1}</a><li>","main.html","测试标题");
alert(str.toString());

对处理大量字符串拼接,在IE6浏览器上表现的速度和性能尤为突出,希望对大家有帮助,如果大家有更好的方法希望留下分享地址,:)

posted @ 2013-07-10 18:06  北京-木木  阅读(560)  评论(0编辑  收藏  举报