Skip to content

Instantly share code, notes, and snippets.

@horitaku1124
Created July 25, 2019 12:51
Show Gist options
  • Save horitaku1124/abeeddbe18eb3ccb9b34f96a7eaaa812 to your computer and use it in GitHub Desktop.
Save horitaku1124/abeeddbe18eb3ccb9b34f96a7eaaa812 to your computer and use it in GitHub Desktop.
format
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