I’m working on a project which will keep track of files with an automatically generated number. However, I need the user to be able to specify the format for this number. For example, if I have a format string file-000000#-v000a
, the first part of the number should always be a minimum of 6 digits long, and the second should be a minimum of 3 digits long, left padded with 0s, like: file-000128-001
, but if they have more or less 0s, it should adjust accordingly.
I’ve tried to come up with something using the String.prototype.replace()
function, but I’m not sure how to calculate the leftPadding
so that it’s the correct number of 0s.
Here’s what I’ve tried so far:
let file_counter = 128;
let version_counter = 1;
// not sure how to calculate these numbers
let leftPadding = 6;
let leftPadding2 = 3;
const format = 'file-000000#-v000a';
const number = format
.replace(/0+#/, file_counter.toString().padStart(leftPadding, '0'))
.replace(/0+a/, version_counter.toString().padStart(leftPadding2, '0'));
console.log(number);
2
Answers
I have since found an answer to this, so if anyone comes looking for something similar, here it is:
A little explanation: In the
replaceValue()
function, I find all places where theregex
is being found, and then I go through each one and replace it with the provided value.This is my solution: