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

问题描述 投票:-1回答:4
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为true,因为有'all',theString2为真,因为有“一些”,theString3为false,因为没有“全部”或“某些”]

javascript arrays logic
4个回答
0
投票
const theStringIsGood = theString.split(' ').some(word => theArray.includes(word))

0
投票
您可以使用string.includes()方法。但是在这种情况下,由于某些内容存在,theString3仍将返回true。您可以创建一个辅助函数来查看字符串是否在数组中:

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; };

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

0
投票
您可以使用正则表达式简单地进行此操作:

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));
祝你好运:)

0
投票
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));
© www.soinside.com 2019 - 2024. All rights reserved.