查找值是否包含在JS中的逗号分隔值中

时间:2012-11-09 18:14:07

标签: javascript string

鉴于这两个字符串:

var first = 'dog,cat,lion';
var second = 'cat';

如何判断第二个var是否是第一个变量中的任何单词(用逗号分隔的单词)?

5 个答案:

答案 0 :(得分:23)

您可以使用Array.indexOf

if( first.split(',').indexOf(second) > -1 ) {
   // found
}

需要IE8支持吗?使用垫片:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

答案 1 :(得分:10)

这样可行:

if( first.match(new RegExp("(?:^|,)"+second+"(?:,|$)"))) {
    // it's there
}

答案 2 :(得分:0)

首先,将String拆分为数组:

var second = 'cat';
var first = 'dog,cat,lion';
var aFirst = first.split(',');

然后循环浏览新阵列

for (var i = 0; i < aFirst.length; i++) {
    if (aFirst[i] == second) {
        alert('jay!');
    }
}

答案 3 :(得分:0)

var first = 'dog,cat,lion';
var stringArray = first.split(',');       
for (var i=0; i<stringArray.length; i++) {
    if (stringArray[i].match("cat")) {
          alert('Its matched');
      }
 }

答案 4 :(得分:0)

var first = 'dog, cat, lion';
var second = 'cat';
// \b is a word boundary
// a word character, \w, consists of letters, digits and underscore
// remove the second paramater "i" if you want case-sensitive match
var containsRE = new RegExp(second, "i"); 
var startsWithRE = new RegExp("\\b"+second, "i"); 
var endsWithRE = new RegExp(second+"\\b", "i"); 
var exactRE = new RegExp("\\b"+second+"\\b", "i"); 
// test exactRE, for example, like so
if(exactRE.test(first)) {
    // matched
}