Posted By

szsk on 08/02/06


Tagged

javascript String layout


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jmonteiro


string_center, rjust, ljust


 / Published in: JavaScript
 

URL: http://snipplr.com/users/szsk/

ruby's String#center, String#rjust, String#ljust on javascript

this code need String.repeat http://snipplr.com/view/699/stringrepeat/

  1. String.prototype.ljust = function( width, padding ) {
  2. padding = padding || " ";
  3. padding = padding.substr( 0, 1 );
  4. if( this.length < width )
  5. return this + padding.repeat( width - this.length );
  6. else
  7. return this;
  8. }
  9. String.prototype.rjust = function( width, padding ) {
  10. padding = padding || " ";
  11. padding = padding.substr( 0, 1 );
  12. if( this.length < width )
  13. return padding.repeat( width - this.length ) + this;
  14. else
  15. return this;
  16. }
  17. String.prototype.center = function( width, padding ) {
  18. padding = padding || " ";
  19. padding = padding.substr( 0, 1 );
  20. if( this.length < width ) {
  21. var len = width - this.length;
  22. var remain = ( len % 2 == 0 ) ? "" : padding;
  23. var pads = padding.repeat( parseInt( len / 2 ) );
  24. return pads + this + pads + remain;
  25. }
  26. else
  27. return this;
  28. }
  29.  
  30. alert( "Ruby".center( 10 ) ); // " Ruby "
  31. alert( "Ruby".rjust( 10 ) ); // " Ruby"
  32. alert( "Ruby".ljust( 10 ) ); // "Ruby "
  33. alert( "Ruby".center( 10, "+" ) ); // "+++Ruby+++"

Report this snippet  

You need to login to post a comment.