只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
想象一下逗号表示“或”。
它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。
有什么方法可以做到吗?
只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
想象一下逗号表示“或”。
它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。
有什么方法可以做到吗?
使用includes(),没有,但你可以通过test()实现REGEX:
var value = /hello|hi|howdy/.test(str);
或者,如果词语来自动态来源:
var words = ['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
即使有且只有一个条件为真,它也能工作:
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);
只要其中一个include返回真值,value就为真,否则,它就为假。这在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
1线路方案:
字符串/ Array.prototype。包括('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)str.toLowerCase().includes(value))) console.log (filteredStrArray);
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) => { 让res = data。Find (el => el == id) 返回res ?真:假; } console.log(findId(dataArray, 'Hi')) // false console.log(findId(dataArray, 'amoos')) // true
这取决于你在什么上下文中使用它。 我在一个对象上使用它来检查是否有任何键有一个空字符串或null作为它的值,它工作
Object.values(object).includes('' || null)
也许晚了,但这里是我的解决方案为一个数组和两个或更多的项目 / 1 | 2 /。Test (['one', 'two', 'three', 'four']。加入(' '))
console.log(/ 1 | 2 /。Test (['one', 'two', 'three', 'four']。加入(' ')))