Skip to content

Instantly share code, notes, and snippets.

@AnkurVyas-BTC
Forked from borgateo/RubyUtils.js
Created March 9, 2017 13:53
Show Gist options
  • Save AnkurVyas-BTC/74d6d9454fe9c05893c681f845eae770 to your computer and use it in GitHub Desktop.
Save AnkurVyas-BTC/74d6d9454fe9c05893c681f845eae770 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+++"
@santosh-btc
Copy link

🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment