如何使用javascript (或Jquery)将文本字符串与数组进行比较并返回匹配值?
例如,如果我有一个数组:
var names = ["John", "Mary", "George"];我有一根绳子:
var sentence = "Did Mary go to the store today?";我想比较字符串和数组,并返回匹配的单词,在本例中是"Mary“。
我已经搜索过了,我找到的所有东西似乎都在比较一个特定的字符串。我要找的是匹配的部分。
谢谢!
发布于 2014-12-18 21:39:24
为了避免John匹配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如果名称位于字符串的开头,或者非alpha数字字符在它的(^|[^a-zA-Z0-9])前面,如果名称位于字符串的末尾,或者非alpha数字字符继承它,则需要匹配名称。因此,这两个捕获之前和之后的名称列表。
收集姓名:
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?");发布于 2014-12-18 21:27:14
你可以这样做:
var matches = [];
for(var i=0;i<names.length;i++){
if(sentence.indexOf(names[i]) != -1){
matches.push(names[i]);
}
}
console.log(matches)发布于 2014-12-18 21:46:24
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);
https://stackoverflow.com/questions/27555971
复制相似问题