I have a function for verifying and possibly modifying postal codes from a test file. It verifies correct string length, that there's a space in the middle of the 6 characters (& if not, to insert one), etc. My regExp test is working, but I'm having trouble inserting a space in the middle of a string.
function fixPostalCode(postalCode) {
var invalidChars =/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d$/i;
postalCode = postalCode.toString().trim();
if (postalCode.length = 6 && invalidChars.test(postalCode.toString())) {
return postalCode.toUpperCase();
}
if (postalCode.length = 5 && postalCode.charAt(3) !== ' ' && invalidChars.test(postalCode.toString())) {
return postalCode.slice(0, 3) + " " + postalCode.slice(3, 6);
} else {
throw 'Invalid postal code';
}
}
The test I'm having trouble with is this:
test('an internal space is added', function () {
const postalCode = 'A1A1A1';
expect(fixPostalCode(postalCode)).toEqual('A1A 1A1');
});
my slice method isn't doing anything to the string.
postalCodebut what you are expecting is the result ofstr. I tried your functions with some values and is always returningreturn postalCode.toUpperCase(). Change the value to str if this is what you are expecting to be.trim()fails. It's because the function doesn't work in general - the regex is wrong. So, when it fails thethrowclause is reached.