只是想知道,是否有一种方法可以向.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
其他回答
使用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
那么['hello', 'hi', 'howdy'].includes(str)呢?
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 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
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);