1

I write this function but it only worked with one string ,

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

will return true

how to make it work with several words

let contains = Str.prototype.contains('hello me want coffe',['hello','want']);
2
  • does your code really work? what is, if the wanted word is not the first one? the early exit in the first iteration makes it impossible to get the wanted result. Commented May 24, 2018 at 9:32
  • Do it in two nested loops. the Outer one should be on the "words" array. Commented May 24, 2018 at 9:37

4 Answers 4

1

You can use the some() method along with the includes() method, instead of your 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)));

Sign up to request clarification or add additional context in comments.

Comments

0

You can use some method in combination with split.

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

Comments

0

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']));

Comments

0

You can use RegExp to look for the strings. The pro to use RegExp is that you can be case insensitive.

// '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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.