How can script to add in leading zero for mailing zip if there 4 digits and also add in the hyphen after the 5th digits.

Here is what I have try but not seem to work. Below are the two different script I have test.

1.

var result = “”;

add(record.fields[“MailingZip”], function (value) { result += value; });

result = result.replace(/[^0-9-]/, “”);

if (/^\d{6}$/.test(result)) {

result = result.substring(0,5) + “-” + result.substring(5);

}

results.html(result);

2.

{

function add(value, operation) {

if(value ===undefined || value === ``""``)

return;

operation(value);

}

var result = ``""``;

add(record.fields[``"MailingZip"``],function (value) { result += value; });

result=``"0"``+result.slice(0,5)+``"-"``+result.slice(5,10);

results.html(result);

}

Hello katie0004,

Here is one example that can work in your case:

var zipCode = record.fields[“MailingZip”];

function FormatZipCode(myZipCode, minLength){

//Note that I’m keeping only the numbers as we re-format the output anyway
myZipCode = myZipCode.replace(/[^0-9]/g, “”);
while (myZipCode.toString().length < minLength+1){
myZipCode= “0” + myZipCode;
}

if(myZipCode.length &gt; 5){
     return myZipCode.substring(0,5)+"-"+myZipCode.substring(5);
 }

 else{
     return myZipCode;
 }

}

results.html(FormatZipCode(zipCode,4));