给定这两个字符串:
var first = 'dog,cat,lion';
var second = 'cat';
我将如何知道第二个变量是否是第一个变量中的任何单词(用逗号分隔的单词)?
给定这两个字符串:
var first = 'dog,cat,lion';
var second = 'cat';
我将如何知道第二个变量是否是第一个变量中的任何单词(用逗号分隔的单词)?
您可以使用Array.indexOf
:
if( first.split(',').indexOf(second) > -1 ) {
// found
}
需要 IE8- 支持?使用垫片:https ://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
这会起作用:
if( first.match(new RegExp("(?:^|,)"+second+"(?:,|$)"))) {
// it's there
}
首先,将您的字符串拆分为一个数组:
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!');
}
}
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');
}
}
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
}