Skip to content

Instantly share code, notes, and snippets.

@rummelonp
Created March 5, 2011 17:40
Show Gist options
  • Save rummelonp/856535 to your computer and use it in GitHub Desktop.
Save rummelonp/856535 to your computer and use it in GitHub Desktop.
JavaScriptでPad
String.prototype.pad = function() {
String.PAD_LEFT = 'STRING_PAD_LEFT';
String.PAD_RIGHT = 'STRING_PAD_RIGHT';
var default_pad_string = ' ';
var default_pad_type = String.PAD_RIGHT;
return function (length, pad_string, pad_type) {
var result = this.toString();
pad_string = pad_string == undefined ? default_pad_string : pad_string.toString();
pad_type = pad_type || default_pad_type;
if (pad_type == String.PAD_LEFT) {
while (result.length < length) {
result = pad_string + result;
}
return result.substr(result.length - length, length);
} else {
while (result.length < length) {
result += pad_string;
}
return result.substr(0, length);
}
};
}();
Number.prototype.pad = function(length) {
return this.toString().pad(length, 0, String.PAD_LEFT);
};
// 'おっぱい'.pad(10, 'おっぱい') => 'おっぱいおっぱいおっ'
// (7).pad(3) => '007'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment