我在Javascript. 我盡力解決,但我錯過了一些邊緣情況。我需要幫助來識別那些丟失的案例
通常當你買東西時,你會被問到你的信用卡號碼、電話號碼或對你最秘密問題的回答是否仍然正確。但是,由于有人可能會越過您的視線,因此您不希望它顯示在螢屏上。相反,我們掩蓋它。
你的任務是撰寫一個函式 maskify,它將:
用 # 屏蔽所有數字 (0-9),除非它們是第一個或最后四個字符。切勿掩蓋少于 6 個字符的信用卡。切勿屏蔽非數字字符。
檔案
掩蔽(cc)
引數: cc: String 任意字符的字串。
保證約束:輸入字串永遠不會為空或未定義。回傳: String 輸入字串,除了第一個和最后四個字符之外的所有字符都替換為“#”。
這是我到目前為止嘗試過的
function maskify (cc) {
if (cc.length < 6) {
let reversed = reverse(cc);
let newString = '';
for (let i = 0; i < reversed.length; i ) {
if (i < 4) {
newString = reversed[i];
} else {
newString = '#';
}
}
return reverse(newString);
} else {
return cc.slice(0, -4).replace(/./g, '#') cc.slice(-4);
}
}
function reverse(str) {
return str.split("").reverse().join("");
}
輸出
should mask the digits of standard credit cards
expected '############0694' to equal '5###########0694'
Completed in 2ms
should not mask the digits of short credit cards
expected '#4321' to equal '54321'
uj5u.com熱心網友回復:
這是我的解決方案:
function maskify (cc) {
// If less than 6 characters return full number
if (cc.length < 6)
return cc;
// Take out first character
let firstChar = cc.charAt(0);
cc = cc.slice(1);
// Replace characters except last 4
cc = cc.replace(/\d(?=.{4,}$)/g, '#');
// Add first character back
cc = firstChar cc;
return cc;
}
// Run every example number
const tests = ["4556364607935616", "4556-3646-0793-5616",
"64607935616", "ABCD-EFGH-IJKLM-NOPQ",
"A1234567BCDEFG89HI", "12345", "", "Skippy"];
tests.forEach((number) => console.log(`Testing: ${number} - Output: ${maskify(number)}`));
我用你的例子的所有數字運行它,它得到了正確的輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437188.html
標籤:javascript 细绳 面具 字符串替换
