我的主要目标是检查字符串是否包含单词数组。如果字符串在单词前面包含$,我不希望它检查字符串中的单词数组,并希望直接console.log它。
我遇到的问题是它没有检查";精确的单词";。例如,如果你放E,文本应该显示出来,因为没有只包含"E"的单词,但它没有显示出来。
例如:
const res = `EU, U.S. REACH DEAL TO RESOLVE BOEING-AIRBUS TRADE DISPUTE
$BA`;
const filters = ["E", "OPEC", "Repo"];
if (!filters.some(element => res.includes(element))) {
console.log(res);
}
另一种方法,我想也许可以使用split方法来检查每个数组项,无论它是否是过滤单词。
var res = `EU, U.S. REACH DEAL TO RESOLVE BOEING-AIRBUS TRADE DISPUTE $BA`;
var filters = ["E", "OPEC", "Repo"];
if (filters.some(element => new RegExp('\b'+element + '\b').test(res))) {
console.log(res);
}
使用带有表达式体的ES6 Array.filter((和箭头函数:
var words = ['get', 'help', 'set', 'moon', 'class', 'code', 'Get', ];
var letter = 'e';
var word = "get";
const output = words.filter(x=>x.includes(letter));
console.log(output);
const output2 = words.filter(x => x.toLowerCase().includes(word));
console.log(output2);
.split()
将每个字符串放入一个小写字符串数组中(分隔符是空格或逗号(。如果要过滤的字符串不止一个,请将它们放入数组中
const strings = ['aaa, BBB, ccc', 'vhko nuu', 'String'];
let arrArr = strings.map(str => {
return str.toLowerCase().split(/[,s]/);
});
// arrArr = [['aaa', 'bbb', 'ccc'], ['vhko', 'nuu'], ['string']]
然后通过.flatMap((strArr, idx)...
运行arrArr(数组(的每个字符串数组,通过.flatMap(str...
运行strArr(字符串数组(的各个字符串
return arrArr.flatMap((strArr, idx) => {
return strArr.flatMap(str => {...
对于每个str(字符串(,在三进制中使用.includes(list)
和.startsWith(char)
来测试>str是否在列表中,或者它是否以特定字符串开始(如果传递了第三个参数char[/em>(。
<IF> list.includes(str) ? <TRUE|THEN> [strings[idx]]
: <ELSE IF> char && str.startsWith(char) ? <TRUE|THEN> [strings[idx]]
: <ELSE|THEN> [];
const strs = [
`EU, U.S. REACH DEAL TO RESOLVE BOEING-AIRBUS TRADE DISPUTE $BA`,
`a, b, C, d, E, f`,
`OPEC reaches agreement`,
`This has opec., repo#, and a dollar$ so this should be ignored`
];
const words = ["e", "opec", "repo"];
const wordFilter = (list, strings, char) => {
let arrArr = strings.map(str => {
return str.toLowerCase().split(/[,s]/);
});
return arrArr.flatMap((strArr, idx) => {
return strArr.flatMap(str => {
return list.includes(str) ? [strings[idx]] :
char && str.startsWith(char) ? [strings[idx]] :
[];
});
});
};
console.log(wordFilter(words, strs, '$'));
我想你可以从这个例子中得到一些想法。点击此处查看jsFiddle
var words = ['get', 'help', 'set', 'moon', 'class', 'code'];
var letter = 'e';
function find(words, letter) {
letter = letter.split(''); //get it to as object the we can use it in every method as follwing
return words.filter(function(word) { //get pne buy one word in words array
return letter.every(function(char) {
return word.includes(char); // return word including the letter that you request
});
});
}
const output = find(words, letter);
console.log(output);