简体   繁体   English

新手问题:我的 function 变量没有改变

[英]Newbie question: my function variables aren't changing

I have a function for verifying and possibly modifying postal codes from a test file.我有一个 function 用于验证并可能修改测试文件中的邮政编码。 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.它验证正确的字符串长度,6 个字符中间有一个空格(如果没有,则插入一个),等等。我的 regExp 测试工作正常,但我在字符串中间插入空格时遇到问题.

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.我的 slice 方法没有对字符串做任何事情。

trim() removes whitespace from both sides of a string not from the middle of string. trim()删除字符串两边的空格,而不是字符串中间的空格。 As I see from your description you are trying to cancel whitespace in the middle of the string which is not possible with trim.正如我从您的描述中看到的那样,您正在尝试取消字符串middle的空格,而修剪是不可能的。 You should use replace你应该使用replace

 function fixPostalCode(postalCode) { let test1 = postalCode.toString().trim(); console.log(test1) ///It will fail let test2 = postalCode.replace(/ +/g, ""); console.log(test2) ///It will be succesfull } fixPostalCode('A1A 1A1');

You're most of the way there, but the order of your space insertion wasn't being picked up by the later Regex as valid.您已经完成了大部分工作,但后来的正则表达式并未将您的空格插入顺序视为有效。 Without changing the regex, your code is functional by swapping the order of your toUpperCase method with the space insertion via slice :在不更改正则表达式的情况下,您的代码可以通过将toUpperCase方法的顺序与通过slice进行的空格插入进行交换来发挥作用:

 function fixPostalCode(postalCode) { var invalidChars = new RegExp(/([ABCEGHJKLMNPRSTVXY]\d)([ABCEGHJKLMNPRSTVWXYZ]\d){2}/i); postalCode = postalCode.toString().trim(); if (invalidChars.test(postalCode.toString())) { postalCode = postalCode.toUpperCase(); } if (postalCode.charAt(3).== ' ') { return postalCode,slice(0. 3) + ' ' + postalCode,slice(3; 6); } else { throw 'Invalid postal code'; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM