I have a number in Javascript, that I know is less than 10000 and also non-negative. I want to display it as a four-digit number, with leading zeroes. Is there anything more e
I know this question is kind of old, but for anyone looking for something similar to String formatting on Java or Python, I have these helper methods:
String.format = (...args) => {
if( args.length == 0 ){
throw new Error("String format error: You must provide at least one argument");
}
const delimiter = "@LIMIT*";
const format = String(args.shift(1,0)).replace(/(%[0-9]{0,}[sd])/g, delimiter+"$1"+delimiter).split(delimiter); // First element is the format
if( [...format].filter(el=>el.indexOf("%")>-1).length != args.length ){
throw new Error("String format error: Arguments must match pattern");
}
if( format.length == 1 && args.length == 0 ){
return String(format);
}
let formattedString = "";
// patterns
const decimalPattern = /%[0-9]{0,}d/;
const stringPattern = /%s/;
if( format.length == 0 ){
throw new Error("String format error: Invalid format");
}
let value = null;
let indexOfParam = 0;
let currPattern = null;
while( args.length > 0 ) {
currPattern = format[indexOfParam];
indexOfParam++;
if( currPattern.indexOf("%")<0 ){
formattedString+=currPattern;
continue;
}
value = args.shift(0,1);
if( decimalPattern.test(currPattern) ){
let numberLength = parseInt(currPattern.replace(/[^0-9]/g,''));
if( isNaN(numberLength) ){
numberLength = 0;
}
formattedString+=numberToLength(value, numberLength);
} else if( stringPattern.test(currPattern) ) {
if( typeof value === 'object' && value.toSource ){
formattedString+=String(value.toSource());
} else {
formattedString+=String(value);
}
} else {
throw new Error("String format error: Unrecognized pattern:"+currPattern);
}
}
return formattedString;
}
const numberToLength = (number, length) => {
length = parseInt(length);
number = String(number);
if( isNaN(length) || isNaN(parseInt(number)) ){
throw new Error("Invalid number passed");
}
while( number.length < length ) {
number = "0" + number;
}
return number;
}