Pad length to ensure 5 values

mdjoseph12
Giga Contributor

Looking for the best way to pad the source value to ensure that the target value is 5 digits, I attempted using the script below:

 

var location = source.u_location;

for(i = location.length;i < 4;i ++){


location = '0' + location;

return location; 


}
1 ACCEPTED SOLUTION

Hi Joseph,

try this and let me know

answer = (function transformEntry(source) {
var maxLength = 5;
var location = padZeroes(source.u_location,maxLength);

function padZeroes(number, length) {
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}

return location;

})(source);

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

 

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

9 REPLIES 9

David Stutter
Tera Guru

Would ServiceNow eventual update their JavaScript version you could use this nice function:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

 

Unfortunately this is not the case.

I tried another funny hacky solution:

 

var MAXLENGTH = 5;
var input = '5';

if(input.length < MAXLENGTH) {
	input = new Array(MAXLENGTH - input.length + 1).join(0) + input;
}

I'll give this a shot

Works thanks!

I tried this method in a source script and its still returning empty 

answer = (function transformEntry(source) {
var maxLength = '5';
var location = source.u_location;
if(location.length < maxLength) {
	location = new Array(maxLength - location.length + 1).join(0) + location;
}
target.location = location;
return location; 


})(source);