How to format leading zero of an environment variable

I have an environment variable that serves as my counter. When I increment that variable, I want to format it with leading zero and concatenate it to another environment variable.

For example,

VAR1 = 0
VAR2 = ABCD

When I increment VAR1, I want to format it as 0001 (with leading zeroes). Then when I concatenate VAR1 to VAR2, VAR2 will now have new value as ABCD0001.

I tried doing this in Pre-request scripts as:

pm.environment.set(“VAR1”, Number(pm.environment.get(“VAR1”)) + 1);
pm.environment.set(“VAR2”, “ABCD” + pm.environment.get(“VAR1”));

but it’s not working as expected.

Appreciate your help. Thanks!

1 Like

You’ll have to store the number as a string, as JavaScript will strip the leading zeroes if its defined as a number.

You can use String.prototype.padStart() - JavaScript | MDN

let n = 1
let pad = String(n).padStart(4, '0'); 
console.log(pad); // '0001'
3 Likes

Hey @lhernandez-ph, I agree with @michaelderekjones on his solution. To apply what he said to your specific use case, you can do this:

const counter = (Number(pm.environment.get('VAR1')) + 1).toString().padStart(4, '0');
pm.environment.set('VAR1', counter);
pm.environment.set('VAR2', `ABCD${counter}`);
1 Like

Thank you @allenheltondev and @michaelderekjones … Cheers!

1 Like