Articles → JavaScript → Stringbuilder In Javascript
Stringbuilder In Javascript
Software Requirements
- Windows any version is installed on your machine.
- Notepad or any text editor for writing code.
Prerequisite Knowledge
- Basic knowledge of JavaScript.
- Basic knowledge of HTML.
- Knowledge of any programming language is an added advantage.
Steps To Follow For Creating Stringbuilder In Javascript
- Create a StringBuilder object.
- Add AppendString method to StringBuilder object using prototype property.
- Add ToStringValue method to StringBuilder object using prototype property.
- 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
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