Created
July 25, 2019 12:51
-
-
Save horitaku1124/abeeddbe18eb3ccb9b34f96a7eaaa812 to your computer and use it in GitHub Desktop.
format
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 formatString(...args) { | |
let format = args[0]; | |
let result = format; | |
let matches = format.match(/(%(s|\d*d))/g); | |
for (let i = 0;i < matches.length;i++) { | |
let replaceFrom = matches[i]; | |
let replaceTo = args[i + 1].toString(); | |
if (replaceFrom === "%s" || replaceFrom === "%d") { | |
result = result.replace(matches[i], replaceTo); | |
} else { | |
let matchDigit = replaceFrom.match(/%(.\d)d/); | |
if (matchDigit) { | |
let pad = matchDigit[1].charAt(0); | |
let repeat = parseInt(matchDigit[1].charAt(1)); | |
if (repeat > replaceTo.length) { | |
while(true) { | |
replaceTo = pad + replaceTo; | |
if (replaceTo.length >= repeat) { | |
break; | |
} | |
} | |
} | |
result = result.replace(matches[i], replaceTo); | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment