字符串 JavaScript 的通配符匹配
javascriptweb developmentobject oriented programming更新于 2025/10/27 6:36:17
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

