所以这是数组:
let arrayToMatch = ["!", "?", ".", ","];
let string = "Something!?"; // true
let string2 = "else!"; // false
let string3 = "yes!!"; // true
// if (string has > 2 elemets from arrayToMatch) { do something }
我想检查一下这些字符串是否至少包含来自上面数组的2个元素。 因此,第一个字符串将匹配,但第二个字符串将不匹配。
编辑:
我不好,如果string =“ !!”,我也希望它匹配例如
答案 0 :(得分:1)
您可以使用reduce
进行计数:
let arrayToMatch = ["!", "?", ".", ","];
let string1 = "Something!?";
let string2 = "Other..";
let string3 = "else!";
let string4 = "nothing";
function hasAtLeastXElements(toMatch, str, count = 2) {
return toMatch.reduce((acc, curr) =>
str.includes(curr)
? acc + str.split('').filter(x => x === curr).length
: acc,
0) >= count;
}
console.log(hasAtLeastXElements(arrayToMatch, string1)); // true
console.log(hasAtLeastXElements(arrayToMatch, string2)); // true
console.log(hasAtLeastXElements(arrayToMatch, string3)); // false
console.log(hasAtLeastXElements(arrayToMatch, string4)); // false
编辑:包括重复项。
答案 1 :(得分:0)
尝试使用此代码检查重复项
let string = "Something!?";
let string2 = "else!";
function matchCharacter(string) {
let arrayToMatch = ["!", "?", ".", ","];
var duplicate = arrayToMatch.filter(function(atm) {
if(string.indexOf(atm) != -1) {
return atm;
}
});
return (duplicate.length >1)?'Duplicate':'not-duplicate';
}
console.log(matchCharacter(string));