gpt4 book ai didi

javascript - 如何从不包含搜索关键字的字符串数组中删除字符串?

转载 作者:行者123 更新时间:2023-11-28 17:29:54 24 4
gpt4 key购买 nike

我有一个字符串数组(testArray)。我需要从数组中删除至少不包含一个 searchTerms 的字符串。testArray 应忽略 searchTerms 的大小写。

编辑:结果数组应包含字符串,即使搜索词是字符串中单词的一部分。

例如:“someright text” 应包含在结果中。

var testArray = [
"I am",
"I am wrong and I don't know",
"I am right and I know",
"I don't know",
"some text",
"I do know"
],
searchTerms = ["I", "right","know"] //or ["i", "right","know"];

$.each(searchTerms, function(index, term) {
var regX = new RegExp(term, "i");
testArray = $.map(testArray, function(item) {
if (regX.test(item)) {
return item;
} else {
return;
}
});
});

console.log(testArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

结果应如下所示,

testArray = [
"I am",
"I am wrong and I don't know",
"I am right and I know",
"I don't know",
"I do know"
]

最佳答案

使用Array.filter , Array.someArray.includes

var testArray = ["I am", "I am wrong and I don't know", "I am right and I know", "I don't know", "some text", "I do know"],
searchTerms = ["I", "right","know"];

searchTerms = searchTerms.map(w => w.toLowerCase());

/* Use filter to filter only those records which have the search term in it. */
var result = testArray.filter((s) => s.split(" ").some((w) => searchTerms.includes(w.toLowerCase())));

console.log(result);

编辑

var testArray = ["I am", "I am wrong and I don't know", "I am right and I know", "I don't know", "some text", "I do know", "someright"],
searchTerms = ["I", "right","know"];

searchTerms = searchTerms.map(w => w.toLowerCase());

/* Use filter to filter only those records which have the search term in it. */
var result = testArray.filter((s) => searchTerms.some(w => s.toLowerCase().includes(w)));

console.log(result);

关于javascript - 如何从不包含搜索关键字的字符串数组中删除字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50698209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com