10

给定这两个字符串:

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

我将如何知道第二个变量是否是第一个变量中的任何单词(用逗号分隔的单词)?

4

5 回答 5

28

您可以使用Array.indexOf

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

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

于 2012-11-09T18:28:11.677 回答
11

这会起作用:

if( first.match(new RegExp("(?:^|,)"+second+"(?:,|$)"))) {
    // it's there
}
于 2012-11-09T18:15:53.313 回答
1

首先,将您的字符串拆分为一个数组:

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!');
    }
}
于 2012-11-09T18:20:08.673 回答
1
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');
      }
 }
于 2012-11-09T18:21:01.777 回答
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
}
于 2012-11-09T19:04:20.057 回答