因此,这会检查所有内容是否都在字符串中,并且只有在这种情况下才返回true。
function check(Entry)
{
var contents = "abcd";
for (var i = 0; i < Entry.length; i++)
if (contents.indexOf(Entry.charAt(i)) < 0) return false;
return true;
}
console.log(check("abc"));
console.log(check("abe"));
我需要一个函数来检查字符串中是否有atleast
个字符,并返回true。
答案 0 :(得分:2)
只需将您当前的功能修改为:
function hasAny(haystack, needles)
{
for (var i = 0; i < heystack.length; i++)
if (needles.indexOf(heystack[i])) > 0)
return true;
return false;
}
或者,您可以使用组合式正则表达式,以提供不区分大小写的选项:
function firstMatch(stack, needles, cis = false , m) {
return (m = stack.match((new RegExp('(['+needles+'])', cis ? 'i' : '' ))))
? m.index : -1;
}
function hasAny(stack, needles, cis ) {
return -1 != firstMatch(stack, needles, cis );
}
console.log(firstMatch(a,b)) // -1
console.log(hasAny(a,b)) // false
// Case Insensitive Examples...
console.log(firstMatch(a,b, true)) // 0, which is the index of where the match is in a
console.log(hasAny(a,b, true)) // true
答案 1 :(得分:1)
函数,用于检查字符串中是否至少有一个字符并返回true
function check(str) {
const contents = 'abcd'.split('');
return str.split('').some(c => contents.includes(c));
}
console.log(check('abc'));
console.log(check('afg'));
console.log(check('fgh'));