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,因为没有“全部”或“某些”]
const theStringIsGood = theString.split(' ').some(word => theArray.includes(word))
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));
祝你好运:)
isIncludeWord
-使用split
和includes
方法查找完全匹配的单词。2)isInclude
-使用some
和includes
查找匹配项。 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));