Posted By

vbchrisw on 11/23/10


Tagged

format String


Versions (?)

String.Format


 / Published in: JavaScript
 

  1. function _StringFormatInline()
  2. {
  3. var txt = this;
  4. for(var i=0;i<arguments.length;i++)
  5. {
  6. var exp = new RegExp('\\{' + (i) + '\\}','gm');
  7. txt = txt.replace(exp,arguments[i]);
  8. }
  9. return txt;
  10. }
  11.  
  12. function _StringFormatStatic()
  13. {
  14. for(var i=1;i<arguments.length;i++)
  15. {
  16. var exp = new RegExp('\\{' + (i-1) + '\\}','gm');
  17. arguments[0] = arguments[0].replace(exp,arguments[i]);
  18. }
  19. return arguments[0];
  20. }
  21.  
  22. if(!String.prototype.format)
  23. {
  24. String.prototype.format = _StringFormatInline;
  25. }
  26.  
  27. if(!String.format)
  28. {
  29. String.format = _StringFormatStatic;
  30. }
  31.  
  32. //Static
  33. var str = String.format("This is a {0} string using the {1} method.","formatted","static");
  34.  
  35. //Inline
  36. var str = "This is a {0} string using the {1} method.".format("formatted","inline");

Report this snippet  

You need to login to post a comment.