DCSIMG
JavaScript String.format & StringBuilder - Client-Side with Basil Goldman

JavaScript String.format & StringBuilder

// String.Format
String.format = function() {
     var s = arguments[0];
        for (var i = 0;i<arguments.length-1;i++){       
            var reg = new RegExp("\\{"+i+"\\}","gm");             
            s = s.replace(reg,arguments[i+1]);
        }

        return s;
}

String.prototype.format = function() {     
    var s = this;
        for (var i = 0;i<arguments.length;i++){         
            var reg = new RegExp("\\{"+i+"\\}","gm");                         
            s = s.replace(reg,arguments[i]);
        }

        return s;  
}

// StringBuilder
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("");
}

// Create a StringBuilder
var output = new StringBuilder();

// Append some text
output.append("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, ");
output.append("sed diem nonummy nibh euismod tincidunt ut lacreet dolore ");
output.append("magna aliguam erat volutpat. ");

var content = "World!!!";

output.append(String.format("{0}{1}","Hello ",content));

// Get the full string value
document.getElementById("context").innerHTML = output.toString();
תגים:,

Comments

# Moshe L said:

There is a benchmark  for your  StringBuilder vs str+= ?

Tuesday, February 19, 2008 5:12 PM

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: