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

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

想象一下逗号表示“或”。

它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。

有什么方法可以做到吗?


当前回答

扩展字符串本机原型:

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

其他回答

使用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

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

Object.values(object).includes('' || null)

(错误答案,不要抄)

另一个!

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)

也许晚了,但这里是我的解决方案为一个数组和两个或更多的项目 / 1 | 2 /。Test (['one', 'two', 'three', 'four']。加入(' '))

console.log(/ 1 | 2 /。Test (['one', 'two', 'three', 'four']。加入(' ')))