使用下面的数组,我想搜索首字母假设在同一个矩阵中有几个单词,它必须搜索每个单词,如果它找到它应该返回一个数组
例子const data= [
"the lions of teranga",
"tiger woods",
"The Truman Show",
"Shutter Island",
"The Gold Rush",
]
]
如果匹配"sh"它应该搜索每个单词并返回
["Shutter Island", "The Truman Show"] but not The Gold Rush
如果匹配"lion "它应该搜索每个单词并返回
["the lions of teranga"]
这是forEach
和RegEx
组合的解之一
const data= [
"the lions of teranga",
"tiger woods",
"The Truman Show",
"Shutter Island",
"The Gold Rush",
]
const filteredData = []
data.forEach(sentence => {
let words = sentence.split(" ")
words.forEach((word,index) => {
if(word.match(/^lions?w/gi)) {
filteredData.push(sentence)
}
})
})
console.log(filteredData)
const data= [
"the lions of teranga",
"tiger woods",
"The Truman Show",
"Shutter Island",
"The Gold Rush",
]
inputData = "lions"
let a = data.filter(e => {
str = e.toLowerCase()
if (str.match(inputData.toLowerCase())){
return e
}
})
console.log(a)
这里的filter返回返回true的对象。在这里,您可以搜索任何单词或字符,并返回一个数组。
//your data array
const data= [
"the lions of teranga",
"tiger woods",
"The Truman Show",
"Shutter Island",
"The Gold Rush",
];
//your search letters,if it will be the same use const instead of var
var search="sh";
//make your search case insensitive
search=search.toLowerCase()
//use for loop to go through every sentence
for(var counter=0;counter<data.length;counter++)
{
//get the array of words
var arrayOfWords=data[counter].match(/b(w+)b/g);
//use for loop to go through every word
for(var counter2=0;counter2<arrayOfWords.length;counter2++)
{
//make word case insensitive
var tempWord=arrayOfWords[counter2].toLowerCase();
//check if the search length does not exid your actuall word
if(search.length<=tempWord.length)
{
//check if first letters match
if(tempWord.slice(0,search.length==search)
{
//first letters match, you can put your logic here
}
else
{
//no match
}
}
else
{
//search exids word
}
}
}