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']);
Mihai Alexandru-Ionut
48.6k14 gold badges106 silver badges132 bronze badges
-
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.Nina Scholz– Nina Scholz2018年05月24日 09:32:10 +00:00Commented May 24, 2018 at 9:32
-
Do it in two nested loops. the Outer one should be on the "words" array.Planet-Zoom– Planet-Zoom2018年05月24日 09:37:42 +00:00Commented May 24, 2018 at 9:37
4 Answers 4
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)));
answered May 24, 2018 at 9:33
Michał Perłakowski
93.4k30 gold badges165 silver badges189 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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']))
answered May 24, 2018 at 9:32
Mihai Alexandru-Ionut
48.6k14 gold badges106 silver badges132 bronze badges
Comments
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']));
answered May 24, 2018 at 9:44
Ramesh Rajendran
38.9k49 gold badges159 silver badges241 bronze badges
Comments
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));
answered May 24, 2018 at 10:04
Orelsanpls
23.7k7 gold badges46 silver badges74 bronze badges
Comments
lang-js