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

时间:2020-07-23 14:19:21

标签: javascript regex string function string-search

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

2 个答案:

答案 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'));