通过jquery或js的逗号分隔值匹配或搜索字符串

时间:2018-10-06 19:55:58

标签: javascript jquery

我想通过js数组将字符串部分匹配/搜索到一个字符串。我的字符串和数组示例如下

var str = "host, gmail, yahoo";
var search = 'new@gmail.com';

我已经尝试过如下操作:

if( str.split(',').indexOf(search) > -1 ) {
   console.log('Found');
}

它应与gmail与字符串new@gmail.com匹配

我正在使用以下引用:https://stackoverflow.com/a/13313857/2384642

5 个答案:

答案 0 :(得分:2)

这里有几个问题。首先,您输入的字符串在逗号后有空格,但是您被逗号分隔 ,因此您将获得' gmail'作为值,这会破坏indexOf()结果。删除空格,或使用split(', ')

第二,您需要遍历split()操作的结果数组,并分别检查search字符串中的每个值。您当前还向后使用indexOf(),即。您正在new@gmail.com中寻找gmail。考虑到这些问题,请尝试以下操作:

var str = "host,gmail,yahoo";
var search = 'new@gmail.com';

str.split(',').forEach(function(host) {
  if (search.indexOf(host) != -1) {
    console.log('Found');
  }
});

还要注意,您可以显式定义主机数组,而无需进行split()

var hosts = ['host', 'gmail', 'yahoo'];
var search = 'new@gmail.com';

hosts.forEach(function(host) {
  if (search.indexOf(host) != -1) {
    console.log('Found');
  }
});

答案 1 :(得分:0)

  

它应与gmail字符串的new@gmail.com匹配

为了获得结果,您需要从搜索字符串中提取 gmail

您可以使用正则表达式来实现:

search.match( /\S+@(\S+)\.\S+/)[1]

var str = "host, gmail, yahoo, qwegmail";
var search = 'new@gmail.com';

if( str.split(', ').indexOf(search.match( /\S+@(\S+)\.\S+/)[1]) > -1 ) {
    console.log(search + ': Found');
} else {
    console.log(search + ': Not found');
}


search = 'asd@qwegmail.com';

if( str.split(', ').indexOf(search.match( /\S+@(\S+)\.\S+/)[1]) > -1 ) {
    console.log(search + ': Found');
} else {
    console.log(search + ': Not found');
}

答案 2 :(得分:0)

如您所见,str中没有子字符串包含search值。因此,您需要反转逻辑。像这样的东西。

var str = "host, gmail, yahoo";
var search = 'new@gmail.com';
var res = str.split(', ').filter(function(el) {
  return search.indexOf(el) > -1;
});
console.log(res);

答案 3 :(得分:0)

使用此代码声明数组,因此您无需将其与','

分开
var str = new Array ("host","gmail","yahoo");

要查找元素,请使用此

    for (i = 0; i < str.length; ++i)
    {
         val = str[i];
         if (val.substring(0) === "gmail")
         {
              res = val;
              break;
         }
    }
    //Use res (result) here

注意:这是我的第一个答案,如果有任何错误,请原谅我...

答案 4 :(得分:0)

随着split方法返回一个数组,您必须遍历该数组并检查是否匹配。

这是一个演示:

// added gmail.com to the string so you can see more matched results(gmail and gmail.com).
var str = "host, gmail, yahoo, gmail.com",
search = 'new@gmail.com',
splitArr = str.replace(/(\,\s+)/g, ',').split(','),
/* the replace method above is used to remove whitespace(s) after the comma. The str variable stays the same as the 'replace' method doesn't change the original strings, it returns the replaced one. */
l = splitArr.length,
i = 0;

for(; i < l; i++) {
  if(search.indexOf(splitArr[i]) > -1 ) {
   console.log('Found a match: "' + splitArr[i] + '" at the ' + i + ' index.\n');
  }
}