如何使用javascript检查string1中是否包含一个或多个字符串

时间:2018-05-24 09:30:34

标签: javascript methods

我写这个函数,但它只能用一个字符串

 contains(input,words) {
      let input1 = input.split(' ');
      for ( var i = 0; i < input1.length; i++ ) { 
      if (input1[i] === words) {
        return true;
      }
      else {
        return false;
        }
      }
     }



let contains = Str.prototype.contains('hello me want coffee','hello');

将返回true

如何使用多个单词

let contains = Str.prototype.contains('hello me want coffe',['hello','want']);

4 个答案:

答案 0 :(得分:1)

您可以使用some()方法和includes()方法,而不是contains()

&#13;
&#13;
console.log(['hello', 'want'].some(x => 'hello me want coffe'.includes(x)));
console.log(['hello', 'want'].some(x => 'me want coffe'.includes(x)));
console.log(['hello', 'want'].some(x => 'me coffe'.includes(x)));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以将some方法与split结合使用。

&#13;
&#13;
let contains = (str, arr) => str.split(' ').some(elem => arr.includes(elem));
console.log(contains('hello me want coffe',['hello','want']))
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试indexOf()逻辑

&#13;
&#13;
function contains(input, words) {
       length = words.length;
    while(length--) {
       if (input.indexOf(words[length])!=-1) {
          return true;
       }else{
         return false;
       }  
      }  
     }


console.log(contains('hello me want coffe',['hello','want']));
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用RegExp查找字符串。使用RegExp的专业人员是您可以不区分大小写。

// 'i' means you are case insensitive
const contains = (str, array) => array.some(x => new RegExp(x, 'i').test(str));

const arr = [
  'hello',
  'want',
];

console.log(contains('hello me want coffe', arr));
console.log(contains('HELLO monsieur!', arr));
console.log(contains('je veux des croissants', arr));