Articles → JavaScript → Stringbuilder In Javascript

Stringbuilder In Javascript






Software Requirements




  1. Windows any version is installed on your machine.
  2. Notepad or any text editor for writing code.

Prerequisite Knowledge




  1. Basic knowledge of JavaScript.
  2. Basic knowledge of HTML.
  3. Knowledge of any programming language is an added advantage.

Steps To Follow For Creating Stringbuilder In Javascript




  1. Create a StringBuilder object.
  2. Add AppendString method to StringBuilder object using prototype property.
  3. Add ToStringValue method to StringBuilder object using prototype property.
  4. Call StringBuilder object and its methods to concatenate string values.

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



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>

Try It


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

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250