繁体   English   中英

如何知道一个字符串是否至少包含 Javascript 中的一个数组元素

[英]How to know if a string includes at least one element of array in Javascript

let theString = 'include all the information someone would need to answer your question'

let theString2 = 'include some the information someone would need to answer your question'

let theString3 = 'the information someone would need to answer your question'

let theArray = ['all', 'some', 'x', 'y', 'etc' ]

theString 为真,因为有 'all',theString2 为真,因为有 'some',theString3 为假,因为没有 'all' 或 'some'

const theStringIsGood = theString.split(' ').some(word => theArray.includes(word))

此代码将句子拆分为每个单词,并检查是否有任何单词与匹配集 theArray 匹配。

您可以使用 string.includes() 方法。 但在这种情况下, theString3 仍然会返回 true,因为 some 在某事中。 您可以创建一个辅助函数来查看字符串是否在数组中:

function findString(arr, str) {
    let flag = false;
    let strArr = str.split(' ');
    arr.forEach(function(s) {
        strArr.forEach(function(s2) {
            if(s === s2) {
                flag = true;
            }
        });
    });
    return flag;
};

现在您可以将数组和字符串之一传递给函数并对其进行测试。

你可以用正则表达式简单地做到这一点:

function ArrayInText(str, words) {
    let regex = new RegExp("\\b(" + words.join('|') + ")\\b", "g");
    return regex.test(str);
}

在正则表达式中 \\b 是单词边界

请注意,如果您自己拆分所有字符串并逐个检查,则会占用大量内存,因为这是一种贪婪的解决方案。 我提供使用 javascript 本机函数的方法。

片段:

 let theString = 'include all the information someone would need to answer your question' let theString2 = 'include some the information someone would need to answer your question' let theString3 = 'the information someone would need to answer your question' let theArray = ['all', 'some', 'x', 'y', 'etc'] function ArrayInText(str, words) { let regex = new RegExp("\\\\b(" + words.join('|') + ")\\\\b", "g"); return regex.test(str); } console.log(ArrayInText(theString, theArray)); console.log(ArrayInText(theString2, theArray)); console.log(ArrayInText(theString3, theArray));

祝你好运 :)

1) isIncludeWord -- 使用splitincludes方法查找精确的单词匹配。
2) isInclude - 使用someincludes查找匹配包含。

 let theString = "include all the information someone would need to answer your question"; let theString2 = "include some the information someone would need to answer your question"; let theString3 = "the information someone would need to answer your question"; let theArray = ["all", "some", "x", "y", "etc"]; const isIncludeWord = (str, arr) => str.split(" ").reduce((include, word) => include || arr.includes(word), false); const isInclude = (str, arr) => arr.some(item => str.includes(item)); console.log(isIncludeWord(theString, theArray)); console.log(isIncludeWord(theString2, theArray)); console.log(isIncludeWord(theString3, theArray)); console.log(isInclude(theString, theArray)); console.log(isInclude(theString2, theArray)); console.log(isInclude(theString3, theArray));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM