检查多个字符中的1个是否在字符串中,如果至少有一个在,则返回true



因此,这会检查是否所有内容都在字符串内,只有在这种情况下才会返回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。

只需将当前函数修改为:

function hasAny(haystack, needles)
{
      for (var i = 0; i < heystack.length; i++)
          if (needles.indexOf(heystack[i])) > 0) 
              return true;
       return false;
}

或者,您可以使用组合regex,为您提供不区分大小写的选项:


    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

函数,用于检查字符串中是否至少有一个字符,并返回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'));

相关内容

最新更新