如果条件推送 contain/match 字符串的值

If condition that pushes values that contain/match a string

我有一个运行良好的完整日历脚本。我有一些过滤器,基本上有以下形式:

$("input[name='event_filter_select']:checked").each(function () {
    // I specified data-type attribute in HTML checkboxes to differentiate
    // between risks and tags.
    // Saving each type separately
    if ($(this).data('type') == 'risk') {
        risks.push($(this).val());
    } else if ($(this).data('type') == 'tag') {
        tagss.push($(this).val());
    }
});

然而 else if 语句应该检查检查的值 'tag' 是否包含在结果集中,而不是结果集中的唯一值(如 == ).

现在我只能过滤只有选中的标签值的结果。但我想过滤掉那些具有标签值的标签。

我认为这是用 match(/'tag'/) 完成的,但我一辈子都想不出如何将其放入 if 语句中。

如果有人能引导我朝着正确的方向前进,我将非常高兴。

试试这个条件。

   /\btag\b/.test($(this).data('type'))

如果您的数据是字符串,例如:tag filter1 filter2 filter3,您可以使用 indexOf-函数 (manual)

代码:

if ($(this).data('type').indexOf("risk") != -1))
   //Action here.

indexOf returns -1 如果找不到文本。

我会简单地做:

...
if ($(this).data('type') == 'risk') {
    risks.push($(this).val());
} else if ($(this).data('type').test(/^tag/) {
    tagss.push($(this).val());
}
...

如果 'tag' 必须位于字符串的开头,则此方法有效。
如果 'tag' 可以在字符串中无处不在,则可以使用 test(/tag/).

您可以使用:

var re = new RegExp('\b' + word + '\b', 'i');

或者如果您希望将单词硬编码(例如,在示例中,单词 test):

var re = /\btest\b/i 

显示以下匹配项的示例:

var input = document.querySelector('input');
var div = document.querySelector('div');
var re;
var match;

input.addEventListener('keyup', function() {
  match = input.value.trim();
  re = new RegExp('\b' + match + '\b', 'i');
  
  if($('div').data('type').match(re))
    div.innerHTML = 'Matched the word: ' + '<strong>' + match + '</strong>';
  else div.innerHTML = 'Did not match the word: ' + '<strong>' + match + '</strong>';
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Word to match:<input></input><br>
Output:
<div data-type='tag tags test'></div>

将上述正则表达式合并到您的代码中后,它应该如下所示:

else if ($(this).data('type').match(/\btag\b/i) { //true for data-type that has `tag` in it.
    tagss.push($(this).val());
}