簡體   English   中英

新手問題:我的 function 變量沒有改變

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

我有一個 function 用於驗證並可能修改測試文件中的郵政編碼。 它驗證正確的字符串長度,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';
    }
}

我遇到問題的測試是這樣的:

  test('an internal space is added', function () {
    const postalCode = 'A1A1A1';
    expect(fixPostalCode(postalCode)).toEqual('A1A 1A1');
  });

我的 slice 方法沒有對字符串做任何事情。

trim()刪除字符串兩邊的空格,而不是字符串中間的空格。 正如我從您的描述中看到的那樣,您正在嘗試取消字符串middle的空格,而修剪是不可能的。 你應該使用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');

您已經完成了大部分工作,但后來的正則表達式並未將您的空格插入順序視為有效。 在不更改正則表達式的情況下,您的代碼可以通過將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