skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have since found an answer to this, so if anyone comes looking for something similar, here it is:

    const format = 'file-000000#-v000a';
    const val1 = `${128}`;
    const val2 = `${1}`;
    
    let number = replaceValue(format, /0*#/g, val1);
    number = replaceValue(number, /0*a/g, val2);
    
    console.log(number);
    
    function replaceValue(format, regex, value) {
        const matches = [];
        let m;
        do {
            m = regex.exec(format)
            if (m)
                matches.push({
                    str: m[0],
                    index: m.index
                })
        } while (m);
    
        for (let match of matches) {
            format = format.replace(match.str, value.padStart(match.str.length - 1, '0'));
        }
    
        return format;
    }

    A little explanation: In the replaceValue() function, I find all places where the regex is being found, and then I go through each one and replace it with the provided value.


  2. This is my solution:

    const format = "file-000000#-v000a",
      val1 = `${128}`,
      val2 = `${1}`;
    
    const helper = (str, val, len) => str.replace(/0+/, val.padStart(len, "0"));
    
    var parts = format.split("-");
    
    parts[1] = helper(parts[1], val1, 6);
    
    parts[2] = helper(parts[2], val2, 3);
    
    var whole = parts.join("-");
    
    console.log(whole);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search