首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript:搜索数组,查看它是否包含部分字符串

Javascript:搜索数组,查看它是否包含部分字符串
EN

Stack Overflow用户
提问于 2014-12-18 21:24:44
回答 3查看 2.4K关注 0票数 1

如何使用javascript (或Jquery)将文本字符串与数组进行比较并返回匹配值?

例如,如果我有一个数组:

代码语言:javascript
复制
    var names = ["John", "Mary", "George"];

我有一根绳子:

代码语言:javascript
复制
   var sentence = "Did Mary go to the store today?";

我想比较字符串和数组,并返回匹配的单词,在本例中是"Mary“。

我已经搜索过了,我找到的所有东西似乎都在比较一个特定的字符串。我要找的是匹配的部分。

谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-12-18 21:39:24

为了避免John匹配John,您需要构建一个正则表达式:

代码语言:javascript
复制
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数字字符继承它,则需要匹配名称。因此,这两个捕获之前和之后的名称列表。

收集姓名:

代码语言:javascript
复制
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);

和一个快速可重用的功能:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-12-18 21:27:14

你可以这样做:

代码语言:javascript
复制
var matches = [];

for(var i=0;i<names.length;i++){
    if(sentence.indexOf(names[i]) != -1){
        matches.push(names[i]);
    }
}

console.log(matches)
票数 0
EN

Stack Overflow用户

发布于 2014-12-18 21:46:24

代码语言:javascript
复制
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);

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27555971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档