Articles → JavaScript → StringBuilder in JavaScript

StringBuilder in JavaScript


























Software requirements









Prerequisite knowledge











Steps to follow for creating StringBuilder in JavaScript













prototype property in JavaScript






<object_name>.prototype.<method_or_property_name>= <value_or_function>;



Creation of StringBuilder object


var StringBuilder = function() {
    this.arr = new Array();
}





AppendString method of StringBuilder object


StringBuilder.prototype.AppendString = function(value) {
    this.arr.push(value);
}





ToStringValue method of StringBuilder object


StringBuilder.prototype.ToStringValue = function() {
    return this.arr.join("");
}





Use StringBuilder object for concatenation of string


var sb = new StringBuilder();
sb.AppendString("This");
sb.AppendString(" is");
sb.AppendString(" a");
sb.AppendString(" StringBuilder");
sb.AppendString(" Example");
alert(sb.ToStringValue());



Output


Picture showing the output of the StringBuilder in JavaScript

Click to Enlarge


Complete Code


<script type="text/javascript">
var StringBuilder = function() {
    this.arr = new Array();
}

StringBuilder.prototype.AppendString = function(value) {
    this.arr.push(value);
}

StringBuilder.prototype.ToStringValue = function() {
    return this.arr.join("");
}

var sb = new StringBuilder();
sb.AppendString("This");
sb.AppendString(" is");
sb.AppendString(" a");
sb.AppendString(" StringBuilder");
sb.AppendString(" Example");
alert(sb.ToStringValue());
</script>



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, August 30, 2012

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250