JavaScript.includes()方法的多个条件

只是想知道,有没有一种方法可以将多个条件添加到.includes方法中,例如:

    var value = str.includes("hello", "hi", "howdy");

想象逗号表示“或”。

它现在询问字符串是否包含Hello,Hi Howdy.所以只有当一个,且只有一个条件为真。

有这样做的方法吗?

253778 次浏览

对于includes(),没有,但您可以通过test()使用regex实现相同的功能:

var value = /hello|hi|howdy/.test(str);

或者,如果单词来自动态源:

var words = ['hello', 'hi', 'howdy'];
var value = new RegExp(words.join('|')).test(str);

正则表达式方法是一个更好的主意,因为它允许您将单词作为实际的单词进行匹配,而不是其他的个单词的子字符串。您只需要将单词边界标记\b,因此:

var str = 'hilly';
var value = str.includes('hi'); //true, even though the word 'hi' isn't found
var value = /\bhi\b/.test(str); //false - 'hi' appears but not as its own word

即使有且仅有一个条件为真,这也应该有效:

var str = "bonjour le monde vive le javascript";
var arr = ['bonjour','europe', 'c++'];


function contains(target, pattern){
var value = 0;
pattern.forEach(function(word){
value = value + target.includes(word);
});
return (value === 1)
}


console.log(contains(str, arr));

您可以使用.some方法引用在这里

some()方法测试数组中是否至少有一个元素 通过由提供的函数实现的测试

// test cases
const str1 = 'hi hello, how do you do?';
const str2 = 'regular string';
const str3 = 'hello there';


// do the test strings contain these terms?
const conditions = ["hello", "hi", "howdy"];


// run the tests against every element in the array
const test1 = conditions.some(el => str1.includes(el));
const test2 = conditions.some(el => str2.includes(el));
// strictly check that contains 1 and only one match
const test3 = conditions.reduce((a,c) => a + str3.includes(c), 0) == 1;


// display results
console.log(`Loose matching, 2 matches "${str1}" => ${test1}`);
console.log(`Loose matching, 0 matches "${str2}" => ${test2}`);
console.log(`Exact matching, 1 matches "${str3}" => ${test3}`);

此外,正如一位用户在下面提到的,“恰好匹配一个”也很有趣。外观如上所述(由OP要求)。这可以通过类似的方法来完成,计算.reduce的交叉点,然后检查它们是否等于1。

不是最好的答案,也不是最干净的,但我认为它更宽容。
例如,如果您想对所有检查使用相同的过滤器。 实际上,.filter()处理一个数组,并返回一个过滤后的数组(我发现它也更容易使用)。

var str1 = 'hi, how do you do?';
var str2 = 'regular string';
var conditions = ["hello", "hi", "howdy"];


// Solve the problem
var res1 = [str1].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
var res2 = [str2].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));


console.log(res1); // ["hi, how do you do?"]
console.log(res2); // []




// More useful in this case
var text = [str1, str2, "hello world"];


// Apply some filters on data
var res3 = text.filter(data => data.includes(conditions[0]) && data.includes(conditions[2]));
// You may use again the same filters for a different check
var res4 = text.filter(data => data.includes(conditions[0]) || data.includes(conditions[1]));


console.log(res3); // []
console.log(res4); // ["hi, how do you do?", "hello world"]

以下是有争议的选项:

String.prototype.includesOneOf = function(arrayOfStrings) {
if(!Array.isArray(arrayOfStrings)) {
throw new Error('includesOneOf only accepts an array')
}
return arrayOfStrings.some(str => this.includes(str))
}

允许您执行以下操作:

'Hi, hope you like this option'.toLowerCase().includesOneOf(["hello", "hi", "howdy"]) // True

这可以通过使用Array和Regex的一些/每个方法来完成。

要检查List(Array)中所有的个单词是否出现在字符串中:

const multiSearchAnd = (text, searchWords) => (
searchWords.every((el) => {
return text.match(new RegExp(el,"i"))
})
)


multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true

要检查List(Array)中任何个单词是否出现在字符串中:

const multiSearchOr = (text, searchWords) => (
searchWords.some((el) => {
return text.match(new RegExp(el,"i"))
})
)


multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false

又一个!

let result


const givenStr = 'A, X' //values separated by comma or space.


const allowed  = ['A', 'B']
const given    = givenStr.split(/[\s,]+/).filter(v => v)


console.log('given (array):', given)


// given contains none or only allowed values:


result = given.reduce((acc, val) => {
return acc && allowed.includes(val)
}, true)


console.log('given contains none or only allowed values:', result)


// given contains at least one allowed value:


result = given.reduce((acc, val) => {
return acc || allowed.includes(val)
}, false)


console.log('given contains at least one allowed value:', result)

你也可以这样做:

const str = "hi, there"


const res = str.includes("hello") || str.includes("hi") || str.includes('howdy');


console.log(res);

每当你的一个包含返回真,值将是真,否则,它将是假。这与ES6配合得非常好。

扩展字符串本地原型:

if (!String.prototype.contains) {
Object.defineProperty(String.prototype, 'contains', {
value(patterns) {
if (!Array.isArray(patterns)) {
return false;
}


let value = 0;
for (let i = 0; i < patterns.length; i++) {
const pattern = patterns[i];
value = value + this.includes(pattern);
}
return (value === 1);
}
});
}

允许您执行以下操作:

console.log('Hi, hope you like this option'.toLowerCase().contains(["hello", "hi", "howdy"])); // True

['hello', 'hi', 'howdy'].includes(str)怎么样?

单线解决方案:

string/array.prototype.includes(' hello '||' hi '||' howdy ');

let words = 'cucumber, mercy, introduction, shot, howdy'
words.includes('hi' || 'howdy' || 'hello') // true
words.includes('hi' || 'hello') // false

const givenArray = ['Hi , how are you', 'how are you', 'howdy, how you doing']
const includeValues = ["hello", "hi", "howdy"]
const filteredStrArray = givenArray.filter(str => includeValues.some(value => str.toLowerCase().includes(value)))


console.log(filteredStrArray);

--[错误答案,请勿复制]--

我希望它能有所帮助

// simple test


let str = "only test "
let checked = (str.includes(['test' && 'only']))
console.log(checked + ' -  ' + str)


你能做到的。

["hello", "hi", "howdy"].includes(str)

DEF一个旧的线程,但仍然得到新的答复。 我没有在搜索结果中看到它,这是使用.includes一次搜索字符串中的多个内容的最简单方法之一。 根据您尝试使用它来执行的操作,只需运行一个for循环,该循环遍历您想要使用.includes检查字符串的项数组。

Const text = ' does this include item3? ';


For(i = 0; i < arr.length; i++)
{if (text.includes(arr[i])){/* do whatever */ } }

如果这些项中的任何一项在该字符串中,它将返回true,然后您可以让它执行任何操作..执行函数、更改变量等。您还可以在If语句中添加如果为false要执行的操作。

但值得注意的是,它将为列表中返回true的每一项执行该代码,因此请确保在要执行的代码中对此进行补偿。

编辑-你也可以把它转换成一个函数,设置它来传递参数,这些参数是你检查字符串是否包含的多个东西,然后让它返回true或false,你可以在函数之外对这些信息做任何事情。

精确的与阵列数据/匹配

const dataArray = ["amoos", "rifat", "hello"];


const findId = ( data, id ) => {
let res = data.find(el => el === id )
return res ? true : false;
}


console.log( findId( dataArray, 'Hi') ) // false
console.log( findId( dataArray, 'amoos') ) // true

这取决于你在什么环境中使用它。 我在一个对象上使用它来检查是否有任何键的值为空字符串或NULL,它起作用了。

Object.values(object).includes('' || null)
string.match( /apple|banana/ ) // <-- Use Regex

也许晚了,但这是我对一个数组和两个或更多项目的解决方案。 /one|two/.test(['one', 'two', 'three', 'four'].join(' '))

console.log(/one|two/.test(['one', 'two', 'three', 'four'].join(' ')))