gpt4 book ai didi

javascript - 使用正则表达式将字符串与数组匹配

转载 作者:行者123 更新时间:2023-11-29 10:36:22 25 4
gpt4 key购买 nike

我用我正在搜索的字符串创建了一个正则表达式:

var re = new RegExp(searchTerm, "ig");

我有一个数组,我想通过这些数组搜索:

var websiteName = [
"google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana",
"slack", "soundcloud", "reddit", "uscitp", "facebook"
];

如果我的搜索词是 reddit testtest test,我在调用匹配函数时不会得到匹配结果:

  for(var i = 0; i < websiteName.length; i = i + 1) {
if(websiteName[i].match(re) != null) {
possibleNameSearchResults[i] = i;
}
}

我如何构建我的正则表达式语句,以便当我搜索我的数组时,如果只有一个单词匹配,它仍然会返回 true?

最佳答案

我想你想要这样的东西:

var searchTerm = 'reddit testtest test';

var websiteNames = ["google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana", "slack", "soundcloud", "reddit", "uscitp", "facebook"];

// filter the websiteNames array based on each website's name
var possibleNameSearchResults = websiteNames.filter(function(website) {

// split the searchTerm into individual words, and
// and test if any of the words match the current website's name
return searchTerm.split(' ').some(function(term) {
return website.match(new RegExp(term, 'ig')) !== null;
});
});

document.writeln(JSON.stringify(possibleNameSearchResults))

编辑:如果您想要索引而不是项目的实际值,您最好使用更标准的 forEach 循环,如下所示:

var searchTerm = 'reddit testtest test',
websiteNames = ["google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana", "slack", "soundcloud", "reddit", "uscitp", "facebook"],
possibleNameSearchResults = []

// loop over each website name and test it against all of
// the keywords in the searchTerm
websiteNames.forEach(function(website, index) {
var isMatch = searchTerm.split(' ').some(function(term) {
return website.match(new RegExp(term, 'ig')) !== null;
});

if (isMatch) {
possibleNameSearchResults.push(index);
}
})

document.writeln(JSON.stringify(possibleNameSearchResults))

关于javascript - 使用正则表达式将字符串与数组匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785655/

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