Skip to content

Instantly share code, notes, and snippets.

@borgateo
Created January 23, 2016 15:20
Show Gist options
  • Save borgateo/38c3f9aa40eba53768a5 to your computer and use it in GitHub Desktop.
Save borgateo/38c3f9aa40eba53768a5 to your computer and use it in GitHub Desktop.
Ruby's String Utils: center, rjust, ljust in JS
/*
* Ruby's String#center, String#rjust, String#ljust
*
* https://jsfiddle.net/6v0bpffm/
*/
function ljust( string, width, padding ) {
padding = padding || " ";
padding = padding.substr( 0, 1 );
if ( string.length < width )
return string + padding.repeat( width - string.length );
else
return string;
}
function rjust( string, width, padding ) {
padding = padding || " ";
padding = padding.substr( 0, 1 );
if ( string.length < width )
return padding.repeat( width - string.length ) + string;
else
return string;
}
function center( string, width, padding ) {
padding = padding || " ";
padding = padding.substr( 0, 1 );
if ( string.length < width ) {
var len = width - string.length;
var remain = ( len % 2 == 0 ) ? "" : padding;
var pads = padding.repeat( parseInt( len / 2 ) );
return pads + string + pads + remain;
}
else
return string;
}
console.log( center( "Ruby" , 10 ) ); // " Ruby "
console.log( rjust( "Ruby", 10 ) ); // " Ruby"
console.log( ljust( "Ruby", 10 ) ); // "Ruby "
console.log( center( "Ruby", 10, "+" ) ); // "+++Ruby+++"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment