Created
January 23, 2016 15:20
-
-
Save borgateo/38c3f9aa40eba53768a5 to your computer and use it in GitHub Desktop.
Ruby's String Utils: center, rjust, ljust in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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