如何按数组检查字符串是否具有匹配的子字符串
How to check if string has a matching substring by array
>问题
我知道如何找出字符串是否包含这样的子字符串,您正在寻找一个单词:
var s = "define foo";
alert(s.indexOf("define") > -1);
但是如何使用数组检查多个不同的单词/子字符串?
示例不起作用的代码,在我看来有意义但不起作用:
query = "Define what is grape juice and how to drink it?"
var terms = ["define", "what is", "how to"];
alert(query.indexOf(terms) > -1);
谢谢~!
试试这个:
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
}
你可以在 jQuery 中使用$.each()
遍历terms
数组,并根据字符串单独检查它们中的每一个。在下面的代码中,我创建了一个名为 matchedTerms
的新 JSON 对象,该对象将在字符串中记录术语及其索引。在此处查看演示:http://jsfiddle.net/teddyrised/ktuuoprp/1/
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
});
});
更好的是:您可以在其中构建一个条件语句,以便matchedTerms
只会生成一个简单的数组。在此处查看演示:http://jsfiddle.net/teddyrised/ktuuoprp/2/
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:如果要执行不区分大小写的匹配,将查询转换为小写会有所帮助,即 newQuery = query.toLowerCase(query);
你想看看一个数组是否包含字符串。 有几种方法可以做到这一点。 这在这里得到了很好的回答。
这里有 2 个选项,从那里复制:
选项 1:
$.indexOf
实际上是支持它的浏览器(现在几乎所有浏览器)中Array.prototype.indexOf
的包装器,同时在不支持它的浏览器中提供填充程序。它本质上等同于在Array.prototype
中添加一个填充程序,这是一种更惯用/JSish的做事方式。MDN 提供了这样的代码。这些天我会选择这个选项,而不是使用jQuery包装器。
选项 2:
jQuery提供$.inArray
:
var found = $.inArray('specialword', categories) > -1;
请注意,inArray 返回找到的元素的索引,因此0
指示该元素是数组中的第一个元素。 -1
表示未找到该元素。
例。
- 如何检查两个字符串是否具有相同的字符,包括特殊字符
- 如何在 AngularJS 中检查字符串是否为空
- $.ajax 检查返回字符串是否为“错误”
- 检查字符串是否在字典内的数组中
- 检查字符串是否包含计算
- 验证字符串是否仅包含 javascript 中的某些字符
- 检查字符串是否等于一个单词和一个数字
- 如何检查字符串是否包含非英语字符列表
- 检查字符串是否包含数组中的某个字符串
- 检测字符串是否与格式说明符字符串匹配
- 如何在javascript中测试字符串是否包含带正则表达式的数字
- 如何检查字符串是否为回文JavaScript〔CLOSED!〕
- 检查字符串是否为有效的html标记
- 检查用户输入的字符串是否准确
- Javascript正则表达式,用于检查字符串是否为有效数字
- 使用AngularJS和Angular Translate如何检查字符串是否已被翻译
- If.else语句检查NaN和空字符串是否在JavaScript中不起作用
- Javascript Regex检查字符串是否包含不属于的单词
- 检查长度为5的子字符串是否在另一个字符串中(已重构)
- 如何检查 NS 字符串是否包含 javascript 函数