Skip to content

Instantly share code, notes, and snippets.

@HubSpotHanevold
Created November 16, 2022 17:24
Show Gist options
  • Save HubSpotHanevold/d4e8d4bda8f5eeced8d802248fe74b19 to your computer and use it in GitHub Desktop.
Save HubSpotHanevold/d4e8d4bda8f5eeced8d802248fe74b19 to your computer and use it in GitHub Desktop.
Formatting zip code to remove characters, spaces and trim to 5 digits
exports.main = async (event, callback) => {
const zip = event.inputFields['zip'];
// REMOVE ANY EMPTY SPACES FROM THE ZIP CODE
let no_spaces_zip = zip.replace(/\s/g, '');
// REMOVE ANY NON-NUMERICAL CHARACTERS
let no_character_zip = no_spaces_zip.replace(/\D/g,'');
// MEASURE THE LENGTH OF THE ZIP CODE
let zip_length = no_character_zip.length;
// IF THE ZIP CODE IS 5 CHARACTERS
if (zip_length == 5) {
let better_zip = no_character_zip;
callback({
outputFields: {
new_zip: better_zip
}
});
// CLEAR THE ZIP VALUE IF IT IS LESS THAN 5 CHARACTERS
} else if (zip_length < 5) {
let better_zip = '-';
callback({
outputFields: {
new_zip: better_zip
}
});
// IF THE ZIP IS BIGGER THAN 5 CHARACTERS SUBSTRING
} else {
// NOTE THAT THIS WOULD CHANGE ANY ZIP +4 VALUES TO ONLY 5 DIGIT ZIP
// ADD CONDITIONS HERE TO ADDRESS ZIP +4 IF YOU WANT TO KEEP
let better_zip = no_character_zip.substring(0,5);
callback({
outputFields: {
new_zip: better_zip
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment