Как проверить, если одна или несколько строк, содержащихся в string1, используя JavaScript - PullRequest
0 голосов
/ 24 мая 2018

Я пишу эту функцию, но она работала только с одной строкой,

 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 голосов
/ 24 мая 2018

Вы можете использовать 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));
0 голосов
/ 24 мая 2018

Вы можете использовать метод some() вместе с методом includes() вместо вашего contains():

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)));
0 голосов
/ 24 мая 2018

try indexOf() logic

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']));
0 голосов
/ 24 мая 2018

Вы можете использовать метод some в сочетании с split.

let contains = (str, arr) => str.split(' ').some(elem => arr.includes(elem));
console.log(contains('hello me want coffe',['hello','want']))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...