JavaScript .includes() 方法的多个条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37896484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
multiple conditions for JavaScript .includes() method
提问by user6234002
Just wondering, is there a way to add multiple conditions to a .includes method, for example:
只是想知道,有没有办法向 .includes 方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
Imagine the comma states "or".
想象一下逗号表示“或”。
It's asking now if the string contains hello, hi orhowdy. So only if one, and only one of the conditions is true.
它现在询问字符串是否包含 hello、hi或howdy。所以只有当一个,而且只有一个条件为真。
Is there a method of doing that?
有没有办法做到这一点?
采纳答案by kevin ternet
That should work even if one, and only one of the conditions is true :
即使只有一个条件为真,这也应该有效:
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));
回答by dinigo
You can use the .some
method referenced here.
您可以使用此处.some
引用的方法。
The
some()
method tests whether at least one element in the array passes the testimplemented by the provided function.
该
some()
方法测试数组中是否至少有一个元素通过了提供的函数实现的测试。
// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';
// does the test strings contains this terms?
var conditions = ["hello", "hi", "howdy"];
// run the tests agains every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));
// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);
回答by Utkanos
With includes()
, no, but you can achieve the same thing with REGEX via test()
:
使用includes()
,不,但您可以通过test()
以下方式使用 REGEX 实现相同的功能:
var value = /hello|hi|howdy/.test(str);
Or, if the words are coming from a dynamic source:
或者,如果这些词来自动态来源:
var words = array('hello', 'hi', 'howdy');
var value = new RegExp(words.join('|')).test(str);
The REGEX approach is a better idea because it allows you to match the words as actual words, not substrings of otherwords. You just need the word boundary marker \b
, so:
REGEX 方法是一个更好的主意,因为它允许您将单词匹配为实际单词,而不是其他单词的子字符串。你只需要词边界标记\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
回答by Thomas Leclerc
You could also do something like this :
你也可以做这样的事情:
const str = "hi, there"
const res = str.includes("hello") || str.includes("hi") || str.includes('howdy');
console.log(res);
Whenever one of your includes return true, value will be true, otherwise, it's going to be false. This works perfectly fine with ES6.
每当您的一个包含返回 true 时,value 将为 true,否则,它将为 false。这与 ES6 完美配合。
回答by Denys Rusov
That can be done by using some/everymethods of Array and RegEx.
这可以通过使用Array 和 RegEx 的一些/所有方法来完成。
To check whether ALLof words from list(array) are present in the string:
要检查字符串中是否存在 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
To check whether ANYof words from list(array) are present in the string:
要检查字符串中是否存在 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
回答by Romingo
Not the best answer and not the cleanest, but I think it's more permissive.
Like if you want to use the same filters for all of your checks.
Actually .filter()
works with an array and return a filtered array (wich I find more easy to use too).
不是最好的答案,也不是最干净的,但我认为它更宽容。就像您想对所有检查使用相同的过滤器一样。实际上.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"]
回答by lsblsb
Another one!
另一个!
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)
回答by James Broad
Here's a controversialoption:
这是一个有争议的选择:
String.prototype.includesOneOf = function(arrayOfStrings) {
if(!Array.isArray(arrayOfStrings)) {
throw new Error('includesOneOf only accepts an array')
}
return arrayOfStrings.some(str => this.includes(str))
}
Allowing you to do things like:
允许您执行以下操作:
'Hi, hope you like this option'.toLowerCase().includesOneOf(["hello", "hi", "howdy"]) // True