Skip to content

Instantly share code, notes, and snippets.

@bidiu
Last active December 9, 2018 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bidiu/1c097768757f9cd9a272ec084bcbaedf to your computer and use it in GitHub Desktop.
Save bidiu/1c097768757f9cd9a272ec084bcbaedf to your computer and use it in GitHub Desktop.
Convert post code
/**
* @param {string} postCode post code
* @return {string|null}
* post code after an attempt converting to canonical format,
* in case conversion cannot be made, null will be returned.
*/
function convertPostCode(postCode) {
if (!postCode || typeof postCode !== 'string') {
// postCode is null, undefined, or non string
return null;
}
var leadingChars = ['K', 'L', 'M', 'N', 'P'];
var invalidChars = ['D', 'F', 'I', 'O', 'Q', 'U'];
// convert to uppercase & remove white spaces and hyphen
postCode = postCode.toUpperCase().replace(/\s|-/g, '');
if (postCode.length !== 6) {
// # of non-whitespace characters is not 6
return null;
}
var firstChar = postCode[0];
if (leadingChars.indexOf(firstChar) < 0) {
// first character is illegal
return null;
}
for (var i = 0; i < postCode.length; i++) {
if (invalidChars.indexOf(postCode[i]) >= 0) {
// contains invalid character
return null;
}
}
// insert space in between
postCode = postCode.slice(0, 3) + ' ' + postCode.slice(3, 6);
if (postCode.match(/^[A-Z]\d[A-Z] \d[A-Z]\d$/g)) {
return postCode;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment