使用javascript(或Jquery)如何将一串文本与数组进行比较并返回匹配值?
例如,如果我有一个数组:
var names = ["John", "Mary", "George"];
我有一个字符串:
var sentence = "Did Mary go to the store today?";
我想比较字符串和数组并返回匹配的单词,在本例中为#34; Mary"。
我搜索过,我发现的所有东西似乎都在比较一个特定的字符串。我正在寻找的是匹配PARTIALS。
谢谢!
答案 0 :(得分:1)
为避免 Johnathon 匹配 John ,您需要构建正则表达式:
var names = ["John", "Mary", "George"];
var regex = new RegExp("(^|[^a-zA-Z0-9])(" + names.join("|") + ")([^a-zA-Z0-9]|$)", "g");
regex.test("Did Johnathon go to the store today?"); // false
regex.test("Did John go to the store today?"); // true
如果名称位于字符串的开头或非字母数字字符位于(^|[^a-zA-Z0-9])
之前,您希望匹配名称,如果名称位于字符串的末尾或非字母数字字符成功([^a-zA-Z0-9]|$)
。因此,在名单列表之前和之后捕获两个。
收集姓名:
var matches = [];
var sentence = "Did John or Mary go to the store today?";
sentence.replace(regex, function(match, $1, $2, $3) {
matches.push($2);
});
console.log(matches);
快速可重复使用的功能:
function getMatchingWords(words, s) {
var matches = [],
regex = new RegExp("(^|[^a-zA-Z0-9])(" + words.join("|") + ")([^a-zA-Z0-9]|$)", "g");
s.replace(regex, function(match, $1, $2, $3) {
matches.push($2);
});
return matches;
}
var matches = getMatchingWords(["John", "Mary", "Billy"], "Did John or Mary go to the store today?");
答案 1 :(得分:0)
你可以这样做:
var matches = [];
for(var i=0;i<names.length;i++){
if(sentence.indexOf(names[i]) != -1){
matches.push(names[i]);
}
}
console.log(matches)
答案 2 :(得分:-1)
var sentence = "Did Mary go to the store today?";
var names = ["John", "Mary", "George"];
var found = [];
names.forEach(function(e) {
if (sentence.toLowerCase().search(e.toLowerCase()) > -1) {
found.push(e);
}
});
alert(found);