只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
想象一下逗号表示“或”。
现在询问字符串是否包含hello,hi或howdy。因此,只有在其中一个条件为真的情况下。
有没有这样做的方法?
只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
想象一下逗号表示“或”。
现在询问字符串是否包含hello,hi或howdy。因此,只有在其中一个条件为真的情况下。
有没有这样做的方法?
['hello', 'hi', 'howdy'].indexOf(str)
-1
&&
什么?
Answers:
即使只有一个条件为真,这也应该起作用:
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
var str1 = 'hi, how do you do?';
var str2 = 'regular string';
// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];
// run the tests against 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);
some()
是一种方法,而不是运算符。否则,很好的答案。
使用includes()
,不,但是您可以通过REGEX通过test()
以下方法实现相同的目的:
var value = /hello|hi|howdy/.test(str);
或者,如果单词来自动态来源:
var words = array('hello', 'hi', 'howdy');
var value = new RegExp(words.join('|')).test(str);
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
您也可以这样做:
const str = "hi, there"
const res = str.includes("hello") || str.includes("hi") || str.includes('howdy');
console.log(res);
每当您的包含之一返回true时,value就会为true,否则它将为false。这与ES6完美配合。
这可以通过使用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
不是最好的答案,也不是最干净的答案,但我认为这是更宽松的。就像您要对所有检查使用相同的过滤器一样。实际.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
另一个!
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)
扩展String本机原型:
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
or
意味着至少一场比赛就足够了。