我写这个函数,但它只能用一个字符串
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']);
答案 0 :(得分:1)
您可以使用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)));
&#13;
答案 1 :(得分:0)
您可以将some
方法与split
结合使用。
let contains = (str, arr) => str.split(' ').some(elem => arr.includes(elem));
console.log(contains('hello me want coffe',['hello','want']))
&#13;
答案 2 :(得分:0)
尝试indexOf()
逻辑
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;
答案 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));