indexOf匹配短语并显示警报

时间:2017-10-31 14:17:05

标签: javascript jquery

我正在尝试检测我的msg中是否有"No matching records found"来执行if/else语句。我知道消息中有一个短语,正在检查console.log('msg', msg);

有人可以告诉我,如果我写错了这行吗?

var hasNoRecords = msg.indexOf(/No matching records found/igm) > -1;

如果hasNoRecords在邮件中找到该短语,我正在尝试显示提醒。但相反,它绕过了消息,好像它不在消息中。

if (hasNoRecords) {
      alert('There are no records found');
    } else {
      $('#pdfiframe').html(msg);
      document.getElementById('pdfiframe').contentWindow.print();
      console.log('hasNoRecords Failed');
    }

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

我不相信indexOf接受正则表达式,除非您创建自己的自定义函数。此外,不是使用正则表达式来忽略大小写,而是可以在字符串对象上使用.toLowerCase将该对象的值转换为全部小写,然后搜索您的值(也必须全部更低)情况)。

您当前的代码可以更改为:

var hasNoRecords = msg.toLowerCase().indexOf("no matching records found") > -1;

如果有帮助,请告诉我。