在JavaScript字符串数组中查找子字符串

在JavaScript字符串数组中查找子字符串,javascript,jquery,string,Javascript,Jquery,String,我需要在字符串数组中查找子字符串的代码。这将找到完整的字符串: var categories = [ "msn.com", "http://gmail.com", "word2" ]; found = $.inArray('http://gmail.com/example', categories); alert(found); // TRUE 但我也希望这是真的: var categories = [ "msn.com", "http://gmail.com", "word2" ]; fou

我需要在字符串数组中查找子字符串的代码。这将找到完整的字符串:

var categories = [ "msn.com", "http://gmail.com", "word2" ];
found = $.inArray('http://gmail.com/example', categories);
alert(found); // TRUE
但我也希望这是真的:

var categories = [ "msn.com", "http://gmail.com", "word2" ];
found = $.inArray('gmail.com/example', categories);
alert(found); // FALSE
最新情况:

found = $.inArray('gmail.com/example', categories) !== -1;


根据文档
$。inArray()
返回找到的元素的索引,如果没有找到,它将返回
-1


因此,如果您对布尔值感兴趣,那么可以如上所述进行尝试。

在您的示例中,您正在查找类别数组中不存在的字符串。示例字符串也比类别中的字符串大

请尝试以下方法:

// this will return the matching value...
var categories = [ "msn.com", "http://gmail.com", "word2" ],
    myString = "gmail.com";

found = $.grep( categories, function ( value, i) {
   return (value.indexOf( myString) >= 0)
});
// found is non-empty array if match

为了从数组中搜索匹配元素,Jquery提供了两种类型的函数

jQuery.inArray( value, array [, fromIndex ] )

您可以使用方法查找文本

var categories = [ "msn.com", "http://gmail.com", "word2" ]
var Item = "gmail.com";

var found = jQuery.grep(categories, function(value, i) {      
  return value.indexOf(Item) != -1
}).length;
您可以使用


你在这里期待什么?您的数组不包含任何等于string
gmail.com/example
的条目。你必须定义什么是
similor
string
gmail.com/example
http://gmail.com/
同一个域,在本例中我希望返回True。这将搜索精确匹配项。。但OP的需求完全不同。我没有DV。@RajaprabhuAravindasamy是的,这与
.indexOf()
类似,但似乎是一个令人困惑的问题…?是的,但当我想搜索
gmail.com/example
时,我想给我True,因为(
gmail.com
)在arrayNo中,而不是在数组中!那么,从另一个角度看,我们是如何做到这一点的呢?是的,但是当我们搜索
http://gmail.com
返回false。请尝试grep-参见扩展answer@Down投票人:你能告诉我为什么在这里投反对票吗?不是我的反对票,但可能是因为我之前的回答几乎是重复的:o)好的,没问题(我在我之前没有看到你的答案,很抱歉重复):)
var categories = [ "msn.com", "http://gmail.com", "word2" ]
var Item = "gmail.com";

var found = jQuery.grep(categories, function(value, i) {      
  return value.indexOf(Item) != -1
}).length;
// this will return the matching value...
var categories = [ "msn.com", "http://gmail.com", "word2" ],
    myString = "gmail.com";


found = categories.reduce( function(previousValue, currentValue, index, array){
    return (previousValue >= 0) ? previousValue : (currentValue.indexOf( myString) >= 0) ? index : -1 ;
}, -1);

// found is index of first match