Created
August 9, 2019 07:25
-
-
Save mugyu/32039fd23a7421e698554eef765604ab to your computer and use it in GitHub Desktop.
String.prototype.padStart() が使えない場合のゼロ埋めなど
This file contains hidden or 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
/** | |
* 文字列のリピート | |
*/ | |
function stringRepeat(length, string) { | |
return Array(length + 1).join(string) | |
} | |
/** | |
* なんかの文字埋め | |
*/ | |
function stringPadding(value, length, string) { | |
if (typeof string === 'undefined') { | |
string = ' '; | |
} | |
return (stringRepeat(length - 1, String(string)) + String(value)).slice(-length); | |
} | |
/** | |
* ゼロ埋め | |
*/ | |
function zeroPadding(value, length) { | |
return (stringRepeat(length - 1, String('0')) + String(value)).slice(-length); | |
} | |
console.log(stringPadding(1, 5)); // 1 | |
console.log(stringPadding(1, 5, '0')); //00001 | |
console.log(stringPadding(1, 5, '*')); //****1 | |
console.log(zeroPadding(10, 5)); //00010 | |
// String.prototype.padStart() | |
console.log("100".padStart(5, "0")); //00100 | |
// String.prototype.repeat() | |
console.log("!".repeat(5)); //!!!!! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment