How to check if string has a matching substring by array
问题
我知道如何找出一个字符串是否包含这样的子字符串,其中您要查找一个单词:
1 2 | var s ="define foo"; alert(s.indexOf("define") > -1); |
但是如何使用数组检查多个不同的单词/子字符串呢?
示例:不工作的代码在我看来是有意义的,但不起作用:
1 2 3 | query ="Define what is grape juice and how to drink it?" var terms = ["define","what is","how to"]; alert(query.indexOf(terms) > -1); |
谢谢~!
可以在jquery中使用
1 2 3 4 5 6 7 8 9 10 11 | var query ="Define what is grape juice and how to drink it?", terms = ["define","what is","how to"], matchedTerms = []; $.each(terms, function(i,v) { var match = query.indexOf(v); matchedTerms.push({ 'term': v, 'index': match }); }); |
更妙的是:您可以在其中构建一个条件语句,以便
1 2 3 4 5 6 7 8 9 10 | var query ="Define what is grape juice and how to drink it?", terms = ["define","what is","how to"], matchedTerms = []; $.each(terms, function(i,v) { var match = query.indexOf(v); if(match > -1) matchedTerms.push(v); }); console.log(matchedTerms); |
P/S:如果要执行不区分大小写的匹配,可以将查询转换为小写,即
试试看:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var phrase = 'texttexttexttexttexttexttext'; var terms = ['word1', 'word2', 'word3']; function check(string) { var match = false; for(var i=0;i<terms.length && !match;i++) { if(string.indexOf(terms[i]) > -1) { match = true; } } return match; } //example if(check(phrase)) { //iftrue } else { //iffalse } |
要查看数组是否包含字符串。有几种方法可以做到。这里回答得很好。
这里有两个选项,复制自:
选项1:
选项2:
jquery提供
1 | var found = $.inArray('specialword', categories) > -1; |
注意,in array返回找到的元素的索引,因此
例子。