JavaScript 匹配字串中的萬用字元
我們被要求編寫一個 JavaScript 函式,該函式接收兩個字串和一個數字 n。該函式匹配這兩個字串,即它檢查這兩個字串是否包含相同的字元。如果兩個字串都包含相同的字元,無論其順序如何,或者如果它們最多包含 n 個不同的字元,則該函式應返回 true,否則該函式應返回 false。
讓我們為該函式編寫程式碼 −
示例
const str1 = 'first string'; const str2 = 'second string'; const wildcardMatching = (first, second, num) => { let count = 0; for(let i = 0; i < first.length; i++){ if(!second.includes(first[i])){ count++; }; if(count > num){ return false; }; }; return true; }; console.log(wildcardMatching(str1, str2, 2)); console.log(wildcardMatching(str1, str2, 1)); console.log(wildcardMatching(str1, str2, 0));
輸出
控制檯中的輸出將是 −
true true false
廣告