js StringBuilder


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function StringBuilder(){
  2. // (C) Andrea Giammarchi - Mit Style License
  3. // http://webreflection.blogspot.com/2008/06/lazy-developers-stack-concept-and.html
  4. if(arguments.length)
  5. this.append.apply(this, arguments);
  6. };
  7. StringBuilder.prototype = function(){
  8. var join = Array.prototype.join,
  9. slice = Array.prototype.slice,
  10. RegExp = /\{(\d+)\}/g,
  11. toString = function(){return join.call(this, "")};
  12. return {
  13. constructor:StringBuilder,
  14. length:0,
  15. append:Array.prototype.push,
  16. appendFormat:function(String){
  17. var i = 0, args = slice.call(arguments, 1);
  18. this.append(RegExp.test(String) ?
  19. String.replace(RegExp, function(String, i){return args[i]}):
  20. String.replace(/\?/g, function(){return args[i++]})
  21. );
  22. return this;
  23. },
  24. size:function(){return this.toString().length},
  25. toString:toString,
  26. valueOf:toString
  27. }
  28. }();
  29.  
  30. //usage
  31. /*
  32. var str = new StringBuilder("a", "b", "c");
  33. str.append("de", "f");
  34. alert(str.length); // 5
  35. alert(str.size()); // 6, the length of the string
  36. alert(str); // abcdef
  37.  
  38. alert(
  39.   new StringBuilder("a", "b", "c").
  40.   appendFormat("{0}{1}{0}", 0, 1).
  41.   appendFormat("???", 1, 2, 3)
  42. );
  43. // abc010123
  44.  
  45. */

URL: http://webreflection.blogspot.com/2008/06/lazy-developers-stack-concept-and.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.