Reputation: 167
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']);
Upvotes: 1
Views: 56
Reputation: 23505
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));
Upvotes: 0
Reputation: 38663
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']));
Upvotes: 0
Reputation: 92471
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)));
Upvotes: 1
Reputation: 48357
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']))
Upvotes: 0